Reputation: 2759
Look at this snippet:
def recur(n):
ds = {}
x=do_foo(n)
if foo(n): ds[n] = recur(x)
else: return x
what i want to ask is ds at first iteration is empty and then it adds on some condition if true. if it recurs, on second iteration it enters at ds[n] = recur(x)
so in this nth iteration ds is again defined as ds = {}.. OR ds retains its previous elements. If it doesn't, then how to retain the elements?
Upvotes: 0
Views: 1830
Reputation: 95722
It is very hard to tell what you want here as the code you posted isn't valid Python, but I think you are asking how to pass some sort of cache down through the calls.
The way to do this is to make the cache an optional parameter. That way you can call your function without a cache or you can pass it through to the recursive calls.
def recur(n, ds=None):
if ds is None: ds = {}
x=do_foo(n)
if foo(n):
ds[n] = recur(x, ds)
else:
return x
Alternatively, use a class which gives you full control over how long the cache will persist:
class Bar(object):
def __init__(self):
self.ds = {}
def recur(self, n):
x=do_foo(n)
if foo(n):
self.ds[n] = self.recur(x)
else:
return x
Upvotes: 2
Reputation: 517
Like any programming language, inside a function you have variables that exist only when the function is running: these are local variables. ds
is a local variable here, and only exists when the function runs. Whenever you run the function again ds
won't be as the first one (imagine you're running two instances of the same program, even if you set the same parameters, there are two distinct situations).
For solving your problem, there are two approaches:
ds
as global (outside any function) and refer it as global ds
in the first line of the functionds
as a parameter to the function (this is the very best alternative to deal with this situation)Upvotes: 0
Reputation: 461
Add ds
as an argument to the function.
def recur(n, ds=None):
ds = ds or {}
#...
recur(n, ds=ds)
Upvotes: 1