Recursive function remembers the last result as an argument
Question:
I’m trying to split a number into powers of 2, but my function remembers the result of my previous call.
from math import log
#split number in powers of 2
#n : number
#lst : the current list of numbers
def spn(n, lst=list()):
if n==1:
lst.append(n)
return lst
else:
#rdy : the ready-to-add number
rdy=2**((log(n+1,2))-1)
lst.append(rdy)
#n-rdy: the new number to evaluate
return spn(n-rdy, lst)
For example:
-
spn(1)
should return [1]
-
spn(3)
should return [2.0, 1.0]
-
spn(7)
should return [4.0, 2.0, 1.0]
But it only works the first time I call the function then after the first call my previous result appears as an argument:
Why does this happen, and how can I fix it?
Answers:
Change your lst
argument default value to None
, and if it is None then instantiate it inside your function.
Read about the Python Gotchas on why using mutable default argument values are bad.
I’m trying to split a number into powers of 2, but my function remembers the result of my previous call.
from math import log
#split number in powers of 2
#n : number
#lst : the current list of numbers
def spn(n, lst=list()):
if n==1:
lst.append(n)
return lst
else:
#rdy : the ready-to-add number
rdy=2**((log(n+1,2))-1)
lst.append(rdy)
#n-rdy: the new number to evaluate
return spn(n-rdy, lst)
For example:
-
spn(1)
should return[1]
-
spn(3)
should return[2.0, 1.0]
-
spn(7)
should return[4.0, 2.0, 1.0]
But it only works the first time I call the function then after the first call my previous result appears as an argument:
Why does this happen, and how can I fix it?
Change your lst
argument default value to None
, and if it is None then instantiate it inside your function.
Read about the Python Gotchas on why using mutable default argument values are bad.