-4

関数はdef expand_fmla(オリジナル)と呼ばれます

この関数への入力変数 original は、特定の形式の文字列です。 original の最初の 2 つの位置には記号*またはが含まれて+いるため、 original の最初の 2 つの位置には および の 4 つの可能性が++, **, +*あり*+ます。後続の位置には、少なくとも 3 つの数字 (0 から 9) があり、繰り返しを含む可能性があります。

この関数は、元の数式と同じ桁数と同じ順序で、桁の間に 2 つの演算記号が交互に含まれる数式を返す必要があります。

例えば:

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

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 に答える