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

2024-09-28 18:58:24 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上我有一个列表[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种独特的数学运算组合,并在列表中的元素上进行迭代?我试过几次,但都有点毛茸茸的


Tags: 函数true列表with运算符数字数学ops
1条回答
网友
1楼 · 发布于 2024-09-28 18:58:24
  • 为了避免从符号中查找运算符,我建议直接使用运算符
  • 那么运算符子列表,应该比值子列表小一个元素,5个值需要4个运算符
  • 要获得所有可能性,请对运算符使用product

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

  • 将运算符应用于上一个值和当前值
  • 您现在可以检查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

相关问题 更多 >