尝试对变量列表进行所有操作组合 [英] trying all combinations of operations on list of variables

查看:49
本文介绍了尝试对变量列表进行所有操作组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个值列表,例如:

I have a list of values like:

values = [1, 2, 3, 4]

,我想尝试此列表上的所有组合,例如:

and I want to try all combinations on this list like:

1 + 2
1 + 3
1 + 4
1 * 2
1 * 3
1 * 4
1 + 2 * 3
1 + 2 * 4
1 + 3 * 4

等。

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

What would be the most straightforward way to get all these possible combinations of operations in the most succinct way possible?

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

I would imagine having two lists, [1,2,3,4] and [+, *, -, /] and then taking all combinations of the numbers of all lengths, and then filling in the blanks with all combinations.

因此选择[1、2、3],然后选择操作的所有排列并将它们组合在一起。这似乎很杂乱,我希望有一种更清晰的方法来编写此代码?

So selecting [1, 2, 3] and then selecting all permutations of the operations and combining them together. This seems messy and I'm hoping there's a clearer way to code this?

推荐答案

这是一个递归解决方案,可从数字和运算符,然后使用 eval 进行计算它:

Here's a recursive solution that builds the expression from numbers & operators and then uses eval to calculate it:

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)))

输出(同等tial):

Output (partial):

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

这篇关于尝试对变量列表进行所有操作组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆