0

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:

enter image description here

Why does this happen, and how can I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user962284
  • 670
  • 1
  • 12
  • 29
  • See also http://stackoverflow.com/questions/10676729/why-does-using-none-fix-pythons-mutable-default-argument-issue – gotgenes Jun 05 '12 at 14:44

1 Answers1

3

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.

Christian Witts
  • 11,375
  • 1
  • 33
  • 46