I’m stumped by this seemingly trivial problem…
I would like to use python to take a string of numbers ("123" for example) and create a list that has all possible expressions where a "+" or "-" (or nothing at all) can be inserted between any numbers.
For the example "123" the list would be:
["123","12+3","12-3","1+23","1+2+3","1+2-3","1-23","1-2+3","1-2-3"]
If the length of the string of numbers is N, then the list should contain 3^(N-1) strings.
I feel like this should be done recursively, but I’m stuck trying to figure out how to return the 3 different options (+,-,None).
I believe that the base case of the function should be:
def options(string):
if len(string) == 1:
return string
else:
#This is where I am stuck
Here’s a slightly hacky, but short solution using
itertools.product():Example:
And here’s a recursive solution:
I think the recursive solution is indeed cleaner here.