vendredi 1 avril 2016

Why I'm getting "maximum recursion depth exceeded"

I just saw an alternative construction for python's if-else statements like (0, 1)[ x > 5] and wanted to try it with recursion but for some reason it's not working. Just forget for a moment that it's unpythonic.

Here is an original code which I'm trying to replace with alternative:

def f(n):
    return 1 if n == 1 else n * f(n - 1)

Alternative, which give recursion problem:

def f(n):
    return (n * f(n - 1), 1)[n == 1]

What is the problem with alternative code?

Aucun commentaire:

Enregistrer un commentaire