trying all combinations of operations on list of variables
<p>I have a list of values like:</p>

<pre><code>values = [1, 2, 3, 4]
</code></pre>

<p>and I want to try all combinations on this list like:</p>

<pre><code>1 + 2
1 + 3
1 + 4
1 * 2
1 * 3
1 * 4
1 + 2 * 3
1 + 2 * 4
1 + 3 * 4
</code></pre>

<p>etc.</p>

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

<p>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.</p>

<p>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?</p>

<p>Here's a recursive solution that builds the expression from numbers &amp; operators and then uses <a href="https://docs.python.org/3.4/library/functions.html#eval"><code>eval</code></a> to calculate it:</p>

<pre><code>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)))
</code></pre>

<p>Output (partial):</p>

<pre><code>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
</code></pre>

python combinations