2012-10-29 68 views
-3

该函数的调用DEF expand_fmla(原始)蟒循环和字符串操作

输入变量给此函数,原来,是与特定格式的字符串:在原始的前两个位置具有符号*+ ,因此原始头两个位置有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' 

我如何做这个,我不明白???

+4

[whathaveyoutried.com](http://whathaveyoutried.com) –

+4

你的问题是什么? ...当然不是请为我做作业吗? –

+2

说真的,你试过了什么。如果你想吃勺子,最好是付钱给你做发展。表明你已经付出了努力,你会得到答案。 “请网络,为我解决我的问题,因为我不想让你远离我 – Sheena

回答

2

这oughtta做到这一点:

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' 

希望这会使用一些itertools食谱有助于

0

,特别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 
+0

我总是喜欢看到itertools的例子。但我觉得将发生器分解成几行会更好,因此读起来并不难。只是一个意见。 – jdi

+0

@jdi你是对的,很难阅读这些单行文本。所以,我试图把它分成多行来使它更清晰。 –

+0

这绝对是一个改进。虽然我指的是将发生器分解成变量。你认为这比看一眼长的内线要容易吗?变量名称倾向于帮助描述意图。 – jdi