在变量列表上尝试所有操作组合

Rob*_*Rob 7 python combinations

我有一个值列表,如:

values = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

我想尝试这个列表上的所有组合,如:

1 + 2
1 + 3
1 + 4
1 * 2
1 * 3
1 * 4
1 + 2 * 3
1 + 2 * 4
1 + 3 * 4
Run Code Online (Sandbox Code Playgroud)

等等

以最简洁的方式获得所有这些可能的操作组合的最直接的方法是什么?

我想象有两个列表,[1,2,3,4]和[+,*, - ,/]然后取所有长度的所有组合,然后用所有组合填充空白.

因此,选择[1,2,3],然后选择操作的所有排列并将它们组合在一起.这看起来很混乱,我希望有一个更清晰的方法来编码吗?

nie*_*mmi 6

这是一个递归解决方案,它从数字和运算符构建表达式,然后用于eval计算它:

vals = [1, 2, 3]
operators = ['+', '*', '-', '/']

def expressions(values):
    # Base case, only one value left
    if len(values) == 1:
        yield values

    # Iterate over the indexes
    for i in range(len(values)):
        # Pop value from given index and store the remaining values
        # to be used with next recursion
        forward = values[:]
        val = forward.pop(i)

        # Yield all value, operator, subexpression combinations
        for op in operators:
            for rest in expressions(forward):
                yield [val, op] + rest

for expr in expressions(vals):
    expr = ' '.join(str(x) for x in expr)
    print('{} = {}'.format(expr, eval(expr)))
Run Code Online (Sandbox Code Playgroud)

输出(部分):

1 + 2 + 3 = 6
1 + 2 * 3 = 7
1 + 2 - 3 = 0
1 + 2 / 3 = 1.6666666666666665
1 + 3 + 2 = 6
1 + 3 * 2 = 7
1 + 3 - 2 = 2
1 + 3 / 2 = 2.5
1 * 2 + 3 = 5
1 * 2 * 3 = 6
1 * 2 - 3 = -1
1 * 2 / 3 = 0.6666666666666666
1 * 3 + 2 = 5
1 * 3 * 2 = 6
1 * 3 - 2 = 1
1 * 3 / 2 = 1.5
1 - 2 + 3 = 2
1 - 2 * 3 = -5
1 - 2 - 3 = -4
Run Code Online (Sandbox Code Playgroud)