python - 如何对 python 说 (a+b) = (b+a) 和 (a*b) = (b*a)
问题描述
我在列表中的数字之间有所有可能的操作组合:
list = ['2','7','8']
7+8*2
8+7*2
2*8+7
2+8*7
2-8*7
8-2/7
etc
我想知道是否可以说像 ('7*2+8' and '8+7*2' and '2*7+8') or (7*8*2 and 2*8*7和 7*2*8) 等是一样的。我想知道如果它是相同的操作,如何只进行一次操作。
这是我创建这些不同操作的代码:
Op = ['+','-','*','/']
array = []
for i in Op:
array.append(string1 + i + string2)
return array
解决方案
如果我很了解你,我想我对你有一个想法。
首先,您需要创建所有可能的数字和表达式排列。你可以这样做:
import itertools
num_list = ['2','7','8']
op = ['+','-','*','/'] * 2 # *2 for the case of same operator twice
num_perm = list(itertools.permutations(num_list))
op_perm = list(itertools.permutations(op, 2)) # We want perm of two operators.
现在,您需要将所有排列合并到一个数学表达式中,这是一个很好的方法:
list_of_experssions = list()
for num in num_perm :
for op in op_perm:
list_of_experssions.append(num[0] + op[0] + num[1] + op[1] +num[2])
最后一步是检查两个表达式的结果是否相等(使用eval
函数)但表达式本身不同:
for exp1 in list_of_experssions:
for exp2 in list_of_experssions:
if eval(exp1) == eval(exp2) and exp1 != exp2:
print(exp1, exp2)
在你的例子中,我们得到了 336 个数学表达式和 2560 对相等的表达式。
推荐阅读
- ios - 将字符串转换为从 Google 返回的 NSDate 始终返回 Nil
- url - WSO2 - 将允许的 URI 长度扩展到最大值
- reactjs - 问题:我可以结合 propTypes 和 Yup 来验证我的输入元素吗?
- python - torbrowser-launcher 因导入 QtCore 而失败
- python - 如何在views.py中的函数在Django中运行时动态地将数据添加到模态体
- security - 如何让burp套件成为pc所有接口的代理?
- apache-spark - spark UI,SQL选项卡是什么意思?
- java - Java Slack Bot:如何在斜杠命令中迭代?
- python - 通过比较文件名和电子表格名称将数据粘贴到电子表格中
- mysql - Docker Keycloak Mysql 卷不保存数据