如何对列表的所有元素执行数学运算?

时间:2020-03-19 09:50:56

标签: python python-3.x math permutation

因此,基本上我有一个列表[40,1,3,4,20],如果要进行排列,我可以返回TRUE,我可以重新排列列表中的数字并结合数学运算,得出总共42个数字。 这些运算符是:(+,-,*)。 例如20 * 4-40 + 3-1 = 42,因此它将为列表true返回[40,1,3,4,20]

对于这个问题,我尝试使用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种独特的数学运算组合并将其迭代到列表中的元素上?我尝试了几件事,但一切都变得有些毛茸茸和令人困惑。.

1 个答案:

答案 0 :(得分:3)

  • 为避免从符号中查找运算符,建议直接使用运算符
  • 然后,运算符子列表应该比值子列表小一个元素,5个值需要4个运算符
  • 要获取所有可能,请为运营商使用product

对于值的每个子列表,对于运算符的每个子列表:计算结果

  • 将运算符应用于上一个值和当前值
  • 您现在可以检查是否等于您的目标值

  • 它与之匹配,具有某些格式,并且您已经完成了表达式

from itertools import permutations, product, chain, zip_longest
from operator import add, sub, mul

def operator_to_symbol(ope):
    return {add: "+", sub: "-", mul: "*"}.get(ope, "")

def format_result(values, ops):
    return " ".join(list(chain(*zip_longest(values, ops)))[:-1])

def evaluate(values, operators):
    v = values[0]
    for idx, val in enumerate(values[1:]):
        v = operators[idx](v, val)
    return v


if __name__ == "__main__":
    perm_values = list(permutations([40, 1, 3, 4, 20], 5))
    comb_operator = list(product([add, sub, mul], repeat=4))

    goal = 42
    for p in perm_values:
        for c in comb_operator:
            v = evaluate(p, c)
            if v == 42:
                print(format_result(map(str, p), list(map(operator_to_symbol, c))), "=", goal)

仅给出一个唯一的结果:

4 * 20 - 40 - 1 + 3 = 42
4 * 20 - 40 + 3 - 1 = 42
4 * 20 - 1 - 40 + 3 = 42
4 * 20 - 1 + 3 - 40 = 42
4 * 20 + 3 - 40 - 1 = 42
4 * 20 + 3 - 1 - 40 = 42
20 * 4 - 40 - 1 + 3 = 42
20 * 4 - 40 + 3 - 1 = 42
20 * 4 - 1 - 40 + 3 = 42
20 * 4 - 1 + 3 - 40 = 42
20 * 4 + 3 - 40 - 1 = 42
20 * 4 + 3 - 1 - 40 = 42