-4

The function is called def expand_fmla (original)

The input variable to this function, original, is a string with a specific format: the first two positions in original have the symbols * or +, hence there are 4 possibilities for the first two positions of original: ++, **, +* and *+. The subsequent positions have digits, at least 3 of them (0 to 9), possibly including repetition.

This function should return a formula which has the same digits and in the same order as in the original formula, and in between the digits the two operation symbols are alternatingly included.

For example:

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'

How can I do this, I do not understand???

4

2 回答 2

2

这应该这样做:

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'

希望这可以帮助

于 2012-10-29T21:18:36.573 回答
0

使用一些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
于 2012-10-29T21:24:27.660 回答