8

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

etc.

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

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.

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?

Rob
  • 3,333
  • 5
  • 28
  • 71
  • can you show us what you attempted to do? – Urban48 Sep 16 '16 at 07:33
  • I recommend [`itertools`](https://docs.python.org/3.5/library/itertools.html). First, choose 2-4 among 4 numbers. Second, permutate them. Third, choose 1-3 among 4 operators. Fourth, permeate them. Fifth, take a number, an operator, a number, an operator, and so on. – Jeon Sep 16 '16 at 07:39
  • 1
    Your suggested solution is the simplest and most straightforward way to do it. – Mukherjee Sep 16 '16 at 07:39
  • 1
    Do you want to have the *results* or the expressions in some form? In any case a recursive solution seems easy. When you have exactly two input values you just call all possible operations with those arguments, when you have more than 2 inputs you take one input, you recursively find all combinations of the remaining inputs and operations and then you apply all operations to the input you excluded and all possible results you obtained from the recursive call. – Bakuriu Sep 16 '16 at 07:40
  • I like the recursive solution, that's actually a pretty great idea – Rob Sep 16 '16 at 07:40
  • 1
    What about precedence? For example, do you want `1+2*3` and `(1+2)*3` – Chris_Rands Sep 16 '16 at 08:04
  • Is `1 + 2 + 3` a valid result set? `+` twice – Moinuddin Quadri Sep 16 '16 at 08:32
  • Added cleaner code without using `eval` as using eval is bad practice and is quite insecure. – Moinuddin Quadri Sep 16 '16 at 08:45

4 Answers4

7

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

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
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • is there a simple way to change your function so that `expressions` takes a second argument `operations`? – Daniel Sep 16 '16 at 10:17
  • @DanielG Yes, just add second argument called `operations`, change iteration to happen over it `for op in operations` and change all the `expression` calls to pass the second argument. I just didn't see much point coding it in since the list of operations is fixed on every call. – niemmi Sep 16 '16 at 10:23
2

How about this one (since order of the operands and operators does matter, we must use permutation) ?

from itertools import chain, permutations

def powerset(iterable):
  xs = list(iterable)
  return chain.from_iterable(permutations(xs,n) for n in range(len(xs)+1) )

lst_expr = []
for operands in map(list, powerset(['1','2','3','4'])):
    n = len(operands)
    #print operands
    if n > 1:
        all_operators = map(list, permutations(['+','-','*','/'],n-1))
        #print all_operators, operands
        for operators in all_operators:
            exp = operands[0]
            i = 1
            for operator in operators:
                exp += operator + operands[i]
                i += 1
            lst_expr += [exp]

print ', '.join(lst_expr)

with the following output:

1+2, 1-2, 1*2, 1/2, 1+3, 1-3, 1*3, 1/3, 1+4, 1-4, 1*4, 1/4, 2+1, 2-1, 2*1, 2/1, 2+3, 2-3, 2*3, 2/3, 2+4, 2-4, 2*4, 2/4, 3+1, 3-1, 3*1, 3/1, 3+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/1, 4-3/2+1, 4-3/2*1, 4*3+2-1, 4*3+2/1, 4*3-2+1, 4*3-2/1, 4*3/2+1, 4*3/2-1, 4/3+2-1, 4/3+2*1, 4/3-2+1, 4/3-2*1, 4/3*2+1, 4/3*2-1
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
1

My solution consumes a list of values and thus applies operations on the order with which arguments are given, as an alternative to normal arithmetic evaluation order. For example, 1 + 3 + 5 + 7, would be (((1 + 3) +5) + 7). However, it takes all possible permutations of values, so all possibilities are listed anyway. It also allows one to give any operations as parameters, even lambda expressions.

I use itertools.

from itertools import combinations_with_replacement
from itertools import permutations
from itertools import product
from itertools import chain

To display all expressions we call:

def list_all(operations, values):
    if len(values) == 1:
        return values
    permutes = []
    ops = []
    expressions = []
    # for 4 values we want combinations with 2, 3 and 4 values.
    for subset in range(2, len(values)+1):
        # One could use combinations instead of permutations if all ops
        # where know to be transitive.
        permutes.append(list(permutations(values, subset)))
        ops.append(list(combinations_with_replacement(operations, subset - 1)))
    for o, v in zip(ops, permutes):
        expressions.append(list(itertools.product(o, v)))
    return expressions

And to evaluate them, execute takes the output of list_all:

def execute(expressions):
    results = []
    # Flatten all expressions into a single iterator
    for ops, arguments in chain.from_iterable(expressions):
        oplist = list(ops)
        arglist = list(arguments)
        res = oplist.pop(0)(arglist.pop(0), arglist.pop(0))
        while len(arglist) > 0:
            res = oplist.pop(0)(res, arglist.pop(0))
        results.append(res)
    return results

Example usage:

from operator import add
from operator import sub
import pprint
expressions = list_all([add, sub, lambda x,y : sqrt(x*x + y*y)], [1, 2, 3, 4])
results = execute(expressions)

# Display list with operators, arguments and results.
pprint.pprint(zip(chain.from_iterable(expressions), results))
Daniel
  • 11,332
  • 9
  • 44
  • 72
0

Below is the simpler and cleaner code to achieve this using operator and itertools.

Also check regarding why not to use eval: Is using eval in Python a bad practice?

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)

Below is the output of above 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
Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126