I have a function that calls itself to increment and decrement a stack.
I need to call it a number of times, and I'd like it to work the same way in subsequent calls
but, as expected, it doesn't re-use the default value.
I've read that this is a newbie trap and I've seen suggested solutions, but I haven't been able
to make any solution work.
It would be nice to be able to "fun.reset"
def a(x, stack = [None]):
print x,' ', stack
if x > 5:
temp = stack.pop()
if x <=5:
stack.append(1)
if stack == []:
return
a(x + 1)
print a(0)
print a(2) #second call
print a(3) #third call
I expected this to work, but it doesn't.
print a(0, [None])
print a(2, [None]) #second call
print a(3, [None]) #third call
Can I reset the function to it's initial state?
Any help would be appreciated.
Just pass stack explicitly when doing recursive call:
def a(x, stack=None):
if stack is None:
stack = [None]
...
a(x + 1, stack)
def a(x, stack = None):
if stack is None:
stack = [None]
...
This problem happens because you modify the default argument, which is mutable. As in Kai's answer, one usually solves this by not modifying the default argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.