【问题标题】:python loops and string manipulation [closed]python循环和字符串操作
【发布时间】:2012-10-29 21:11:16
【问题描述】:

函数名为def expand_fmla(原创)

这个函数的输入变量 original 是一个具有特定格式的字符串:original 的前两个位置有符号*+,因此 original 的前两个位置有 4 种可能: ++, **, +**+。后面的位置有数字,至少有 3 个(0 到 9),可能包括重复。

这个函数应该返回一个与原始公式具有相同数字和顺序的公式,并且在数字之间交替包含两个操作符号。

例如:

expand_fmla('++123') should return '1+2+3'

expand_fmla('+*1234') should return '1+2*3+4'

expand_fmla('*+123456') should return '1*2+3*4+5*6'

我怎么能这样,我不明白???

【问题讨论】:

  • 你的问题是什么? ...肯定不是请为我做作业吗?
  • 说真的,你试过什么。如果你想吃勺子,最好花钱请人为你做开发。表明你已经付出了努力,你会得到答案。 “请上网,为我解决我的问题,因为我不想”不会让你走得太远

标签: python string list loops


【解决方案1】:

应该这样做:

def expand_fmla(original):
    answer = []
    ops = original[:2]
    nums = original[2:]
    for i,num in enumerate(nums):
        answer.extend([num, ops[i%2]])
    return ''.join(answer[:-1])

In [119]: expand_fmla('+*1234')
Out[119]: '1+2*3+4'

In [120]: expand_fmla('*+123456')
Out[120]: '1*2+3*4+5*6'

In [121]: expand_fmla('++123')
Out[121]: '1+2+3'

希望对你有帮助

【讨论】:

    【解决方案2】:

    使用一些 itertools 食谱,特别是 itertools.cycle() 在这里会很有用:

    from itertools import *
    def func(x):
        op=x[:2]                             # operators
        opn=x[2:]                            # operands
        cycl=cycle(op)                       # create a cycle iterator of operators
    
        slice_cycl=islice(cycl,len(opn)-1)   # the no. of times operators are needed
                                             # is 1 less than no. of operands, so
                                             # use islice() to slice the iterator
    
        # iterate over the two iterables opn and          
        # slice_cycl simultanesouly using
        # izip_longest , and as the length of slice_cycl 
        # is 1 less than len(opn), so we need to use a fillvalue=""
        # for the last pair of items
    
        lis=[(x,y) for x,y in izip_longest(opn,slice_cycl,fillvalue="")]   
    
    
        return "".join(chain(*lis))
    
    print func("++123")
    print func("+*123")
    print func("+*123456")
    print func("*+123456")
    

    输出:

    1+2+3
    1+2*3
    1+2*3+4*5+6
    1*2+3*4+5*6
    

    【讨论】:

    • 我总是喜欢看 itertools 的例子。但我觉得将生成器分成几行会好得多,这样阅读起来就不那么难了。只是一个意见。
    • @jdi 你是对的,很难阅读这些单行字。因此,我尝试将其分成多行以使其更清晰。
    • 这绝对是一个进步。尽管我指的是将生成器拆分为变量。你认为这会比看到长的一个班轮更容易吗?变量名称往往有助于描述意图。
    猜你喜欢
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2013-07-21
    • 1970-01-01
    相关资源
    最近更新 更多