With a string of numbers generate variations with addition, subtraction or nothing to make 100

Question:

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?

Asked By: cookiemonster328

||

Answers:

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

Answered By: ScootCork
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
Answered By: Franck Perrin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.