Recursive function defined within function => NameError

Ralf Muschall rmuschall.fih at
Thu Feb 17 18:03:24 EST 2000

Michael Ströder schrieb:

I'd rename the inner "fak" into something like "aux". It does
not matter to python (due to the completely separated scopes),
but to the poor human who has to read the code:

def func1():
  def fak(n,aux):
    if n>1:
      return n*aux(n-1,aux)
      return n
  print fak(6,fak)

An alternative (but essentially similar) way would be to use Y:

def Y(f):
   return lambda x,f=f:f(Y(f))(x)

def func1(n):
   def fak(f,n=n):
       if n>1:
          return n*f(n-1)
          return 1
   return Y(fak)(n)

print func1(6)

Typos are mine (I wrote it just in the newsreader without
testing). The advantage of this method is the fact that you
can replace the Y with a memoizing variant and get memoization
for all your local recusive functions. Besides that, it looks
more sophisticated and can be used to show off.


More information about the Python-list mailing list