-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'
任何想法如何生成上述所有不同的组合?
我给了一个字符串(例如“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'
任何想法如何生成上述所有不同的组合?
这是实现这一一种方法:
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(...)
(这次没有*
这可能会更清洁一点)替换它。
yes但我需要'+'&' - '&'*'和'/' – bhoots21304
以上方法的组合不会给我那 like 1 + 2 * 3-4 + 5 + 6-7 + 8 – bhoots21304
谢谢你..那就是我想要的..但是你可以解释这个代码..就像包“产品”做什么.. && ..什么是“zip”命令 – bhoots21304