I'm excited to ask my first question here. I've run into some problems with recursion. I am coding with Python.
I am using a dictionary to store previously solved numbers in a mathematical sequence. I then check this dictionary when solving later sequences to make the program run faster. Each key represents solved 'starting numbers,' the value represents how long it took the sequence to take the starting number and take it down to 1 using a particular formula.
I'm solving the problem using recursion, which itself is very easy but there's more to it for me.
Each recursive step gives me the opportunity to update a different key in the library, but I am unable to find a way to do this.
So where a sequence might look like 13 -> x -> y -> z ... -> 1, what would you do to not only update the 13 key with value, but also the x, y, x values in the dictionary during the same recursive path? Right now I'm only able to update one number per sequence.
cache = {1:1}
def solve(number):
if cache.has_key(number):
return cache[number]
else:
if condition one..
return 1 + solve(number * formula 1)
else condition two...
return 1 + solve(number * formula 2)
for x in xrange(1,1000):
cache[x] = solve(x) <-- right now only cache[x] is being updated.
Thank you!