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>Below is the simpler and cleaner code to achieve this using <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>operator</code></a> and <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code></a>.</p>

<p>Also check regarding why not to use <code>eval</code>: <a href="http://stackoverflow.com/a/1832957/2063361">Is using eval in Python a bad practice?</a></p>

<pre><code>from itertools import product, combinations, chain
from operator import add, sub, mul, div, mod, floordiv

my_list = [1, 2, 3, 4, 0]
my_operations = {'+': add, '-': sub, '/': div, '*': mul, '%': mod, '//': floordiv}

for nums, action in chain(product([i for i in combinations(my_list, 2)], my_operations)):
    try:
        result = my_operations[action](nums[0], nums[1])
    except ZeroDivisionError:
        result = 'infinite'
    finally:
        print '{} {} {} = {}'.format(nums[0], action, nums[1], result)
</code></pre>

<p>Below is the output of above code:</p>

<pre><code>1 // 2 = 0
1 % 2 = 1
1 + 2 = 3
1 * 2 = 2
1 - 2 = -1
1 / 2 = 0
1 // 3 = 0
1 % 3 = 1
1 + 3 = 4
1 * 3 = 3
1 - 3 = -2
1 / 3 = 0
1 // 4 = 0
1 % 4 = 1
1 + 4 = 5
1 * 4 = 4
1 - 4 = -3
1 / 4 = 0
1 // 0 = infinite
1 % 0 = infinite
1 + 0 = 1
1 * 0 = 0
1 - 0 = 1
1 / 0 = infinite
2 // 3 = 0
2 % 3 = 2
2 + 3 = 5
2 * 3 = 6
2 - 3 = -1
2 / 3 = 0
2 // 4 = 0
2 % 4 = 2
2 + 4 = 6
2 * 4 = 8
2 - 4 = -2
2 / 4 = 0
2 // 0 = infinite
2 % 0 = infinite
2 + 0 = 2
2 * 0 = 0
2 - 0 = 2
2 / 0 = infinite
3 // 4 = 0
3 % 4 = 3
3 + 4 = 7
3 * 4 = 12
3 - 4 = -1
3 / 4 = 0
3 // 0 = infinite
3 % 0 = infinite
3 + 0 = 3
3 * 0 = 0
3 - 0 = 3
3 / 0 = infinite
4 // 0 = infinite
4 % 0 = infinite
4 + 0 = 4
4 * 0 = 0
4 - 0 = 4
4 / 0 = infinite
</code></pre>

python combinations