Neysofu Neysofu - 6 months ago 16
Python Question

f = lambda n:(1,f(n-1)*n)[n>1] gives RunTimeError in Python 3

I'm golfing a factorial function in Python 3, but my lambda doesn't work:

f = lambda n:(1,f(n-1)*n)[n>1]


It raises this error:

File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <lambda>
# Many other identical lines...
RuntimeError: maximum recursion depth exceeded


Where's the problem?

Answer

Tuples aren't lazily evaluated. Even though f(0) will select the first element in the tuple (1, f(-1)*0), it still has to call f(-1) before it can do so. And before f(-1) can return, it has to call f(-2), and so on forever.

Consider using the inline conditional instead, which does delay evaluation until it knows which branch it's going to go down.

f = lambda n:1 if n <= 1 else f(n-1)*n
print f(10)