2016-12-27 77 views
-1

我給了一個字符串(例如「12345678」)。 我想用+,-,*, /生成不同的組合。 喜歡:在字符串中生成不同的排列/組合

'1+2+3+4+5+6+7+8' 
'1+2*3-4+5+6-7+8' 
'1-2+3+4*5+6-7*8' 
'1-2-3-4+5*6+7+8' 
'1+2+3+4+5+6*7*8' 
'1-2+3-4+5-6+7-8' 

任何想法如何生成上述所有不同的組合?

回答

2

這是實現這一一種方法:

from itertools import product 

numbers = "123456" 
for operators in product('+-*/', repeat=len(numbers)-1): 
    ret = numbers[0] 
    for op, n in zip(operators, numbers[1:]): 
     ret += op+n 
    print(ret) 

zip創建對兩個迭代的元件。其餘的只是字符串操作(而不是一個很好的方式)。

這是一個小更緊湊的(和Python的?),還有一些更神奇的itertools

from itertools import product, zip_longest, chain 

numbers = "123456" 
operators = '+-*/' 
for ops in product(operators, repeat=len(numbers)-1): 
    print(''.join(chain(*zip_longest(numbers, ops, fillvalue='')))) 

product是有據可查的。與zip_longest我創建一個迭代器,將產生配對('1', '+') , ('2', '*'), ... , ('6', '')(最後一項填充fillvalue; ops是一個元素短於numbers)。 chain(*...)成語是一種簡單的方法來壓扁元組以獲得字符串'1', '+', '2', '*', ..., '6', ''上的迭代器。那麼我簡單地join這些字符串。

如果你不喜歡chain(*...)部分,你可以用chain.from_iterable(...)(這次沒有*這可能會更清潔一點)替換它。

+0

yes但我需要'+'&' - '&'*'和'/' – bhoots21304

+0

以上方法的組合不會給我那 like 1 + 2 * 3-4 + 5 + 6-7 + 8 – bhoots21304

+0

謝謝你..那就是我想要的..但​​是你可以解釋這個代碼..就像包「產品」做什麼.. && ..什麼是「zip」命令 – bhoots21304