首页 > 解决方案 > 如何对 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

标签: pythonlistoperators

解决方案


如果我很了解你,我想我对你有一个想法。

首先,您需要创建所有可能的数字和表达式排列。你可以这样做:

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 对相等的表达式。


推荐阅读