首页 > 解决方案 > 如何对列表的所有元素执行数学运算?

问题描述

所以基本上我有一个列表[40,1,3,4,20],如果有一个排列,我想返回 TRUE,我可以重新排列列表中的数字与数学运算混合,得到总共 42 个。这些运算符是:(+,-,*)。一个例子是 20 * 4 - 40 + 3 - 1 = 42,因此它会返回truelist [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 种独特的数学运算组合并在列表中的元素上进行迭代?我已经尝试了几件事,但一切都变得有点毛茸茸和令人困惑..

标签: pythonpython-3.xmathpermutation

解决方案


  • 为了避免从符号中寻找运算符,我建议直接使用运算符
  • 那么操作符子列表,应该比值子列表小一个元素,5个值需要4个操作符
  • 获得所有可能性,product用于运营商

对于每个 value 子列表,对于 operator 的每个子列表:计算结果

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

  • 它匹配,一些格式,你完成了一个表达式

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

推荐阅读