Using plain Python or any Python libraries, how would you go about finding all possible combinations of elements in a list l
that equal a given value val
using addition, subtraction, or multiplication? Assume the length of the list isn't always the same, assume each element in the list can only be used once in each combination, and assume there isn't any use of parentheses.
For example:
- We're given a list of numbers:
l = [1,2,3,4]
- We're given a value equaling the combination of values:
val = 6
- The output would include the following:
[2,4]
, since2+4=6
- And
[4,2]
, since4+2=6
- And
[1,3,2]
, since1+3+2=6
- And
[1,2,4]
, since1*2+4=6
- etc.
I've tried using itertools.permutations:
>>> from itertools import permutations
>>> l = [1,2,3,4]
>>> val = 6
>>> correct_combos = []
>>> for i in range(1, len(l)+1):
... for p in permutations(l, r=i):
... if sum(p) == val:
... correct_combos.append(p)
I'm able to only implement the code for testing the sum of all combinations of elements in the list.
>>> print(correct_combos)
[(2, 4), (4, 2)]
I'm stuck on finding permutations of elements in the list using a combination of addition, subtraction, and multiplication.
x*(y+z)
? – Ajax1234*
, then+
or-
. – dkhara