python - 如何对列表的所有元素执行数学运算?
问题描述
所以基本上我有一个列表[40,1,3,4,20]
,如果有一个排列,我想返回 TRUE,我可以重新排列列表中的数字与数学运算混合,得到总共 42 个。这些运算符是:(+,-,*)。一个例子是 20 * 4 - 40 + 3 - 1 = 42,因此它会返回true
list [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 种独特的数学运算组合并在列表中的元素上进行迭代?我已经尝试了几件事,但一切都变得有点毛茸茸和令人困惑..
解决方案
- 为了避免从符号中寻找运算符,我建议直接使用运算符
- 那么操作符子列表,应该比值子列表小一个元素,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
推荐阅读
- haskell - Haskell,找到具有最小第二个元素的元组,如果有两个相同的第二个元素值的元组,则用第一个元素排序
- c++ - 如何以简单的方式更改堆上 QVector 数组中包含的对象的值?
- python - 正则表达式查找带有下划线和可选扩展名的文件
- google-cloud-platform - Google Cloud Storage 网络托管:将 http 重定向到 https
- google-sheets - 我可以使用电子表格更新 Google 表单问题吗?
- reactjs - TypeError:compiler.plugin 不是 ReactLoadablePlugin.apply 的函数
- python - 如何在 DRF 模型字段中仅显示和使用日期时间中的天数并发送请求以填充该字段
- python - 使用 SELECT 语句执行值
- apache - 403 Forbidden In Asp.Net Core app with Apache
- sql - isnull 和列创建