2

I have a string of numbers, string="123456789" and I would like to print all variations, inserting addition, subtraction or nothing between the numbers to make 100.The order of numbers most remain unchanged.

Example: 1+2+3-4+5+6+78+9=100

I am not sure how to even start. I thought of making a list of all possible combinations of +-x (x stands for nothing) and inserting each one and testing it, but that seems that it will take a long time. Any suggestions?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 1
    3^8 is only 6561 so enumerating all possibilities looks pretty feasible – iBug May 03 '21 at 13:30
  • And how do I go about doing that? I need 8 values, but only have 3 things to put in them. The codes that I found support only less values that the starting length (for example itertools.combinations) – cookiemonster328 May 03 '21 at 13:37

2 Answers2

5

You could do so using product and zip_longest from the itertools module. We build up all possible combinations, and then evaluate them filtering for only the ones that evaluate to 100.

from itertools import product, zip_longest

operations = ['-', '+', '']
s = '123456789'

combinations = (zip_longest(s, ops, fillvalue='') for ops in product(operations, repeat=8))

to_eval = (''.join(i + j for i, j in combination) for combination in combinations)

print([i for i in to_eval if eval(i) == 100])

>>> ['1+2+3-4+5+6+78+9', '1+2+34-5+67-8+9', '1+23-4+5+6+78-9', '1+23-4+56+7+8+9', '12-3-4+5-6+7+89', '12+3-4+5+67+8+9', '12+3+4+5-6-7+89', '123-4-5-6-7+8-9', '123-45-67+89', '123+4-5+67-89', '123+45-67+8-9']

eval() is not inherently bad, its just that it can cause major security problems if any user input can get in the thing you are evaluating (which is not the case here). Doing this for a personal project is fine. In production environments you might want to parse the strings yourself or find a different approach.

Note for optimizations have a look here: Most pythonic way to interleave two strings

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
ScootCork
  • 3,411
  • 12
  • 22
  • 1
    Eval is not inherently bad, its just that it can cause major security problems if any user input can get in the thing you are evaluating (which is not the case here). Doing this for a personal project is fine. In production environments you might want to parse the strings yourself or find a different approach. – ScootCork May 03 '21 at 14:14
0
a = ['+', '-', '']
nb = '123456789'
target = 100
N = len(nb)-1

for n in range(3**N):
    attempt = nb[0]
    for i in range(N):
        attempt += a[n % 3]
        attempt += nb[i+1]
        n = n // 3
    if eval(attempt) == target:
        print(attempt, ' = ', target)

leads to

1+23-4+56+7+8+9  =  100
12+3-4+5+67+8+9  =  100
1+2+34-5+67-8+9  =  100
1+2+3-4+5+6+78+9  =  100
123-4-5-6-7+8-9  =  100
123+45-67+8-9  =  100
1+23-4+5+6+78-9  =  100
12-3-4+5-6+7+89  =  100
12+3+4+5-6-7+89  =  100
123-45-67+89  =  100
123+4-5+67-89  =  100