Skip to content
Advertisement

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

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?

Advertisement

Answer

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

Advertisement