所以基本上我有一个列表[40,1,3,4,20]
,如果有一个排列,我想返回TRUE,在这个排列中,我可以重新排列列表中的数字,混合数学运算,得到总数42。
这些运算符是:(+,-,*)。
例如,20*4-40+3-1=42,因此它将为列表[40,1,3,4,20]
返回true
对于这个问题,我尝试使用itertool的组合替换函数来获得所有可能的运算符组合的列表:
from itertools import permutations, combinations, combinations_with_replacement
ops = []
perm = permutations([40,1,3,4,20], 5)
comb = combinations_with_replacement(["+","-","*"], 5)
for i in list(comb):
ops.append(i)
print(ops)
这给了我:
[('+', '+', '+', '+', '+'),
('+', '+', '+', '+', '-'),
('+', '+', '+', '+', '*'),
('+', '+', '+', '-', '-'),
('+', '+', '+', '-', '*'),
('+', '+', '+', '*', '*'),
('+', '+', '-', '-', '-'),
('+', '+', '-', '-', '*'),
('+', '+', '-', '*', '*'),
('+', '+', '*', '*', '*'),
('+', '-', '-', '-', '-'),
('+', '-', '-', '-', '*'),
('+', '-', '-', '*', '*'),
('+', '-', '*', '*', '*'),
('+', '*', '*', '*', '*'),
('-', '-', '-', '-', '-'),
('-', '-', '-', '-', '*'),
('-', '-', '-', '*', '*'),
('-', '-', '*', '*', '*'),
('-', '*', '*', '*', '*'),
('*', '*', '*', '*', '*')]
我将如何应用这21种独特的数学运算组合,并在列表中的元素上进行迭代?我试过几次,但都有点毛茸茸的
product
对于每个值子列表,对于每个运算符子列表:计算结果
您现在可以检查is是否等于您的目标值
它匹配了一些格式,您就可以使用一个表达式了
仅给出一个唯一的结果:
相关问题 更多 >
编程相关推荐