0

Consider the two following recursive functions that calculate the factorial of an input that I naively thought would be the same:

  1. fact = lambda x: 1 if x == 0 else x * fact(x-1)

  2. fact = lambda x: [x*fact(x-1),1][x==0]

The first runs fine but the second give me the error RuntimeError: maximum recursion depth exceeded. This is true for for inputs where x==0 and x!=0.

Why can't the lambda function handle the second case?

1 Answer 1

2

They are not the same. In the second variant both expressions in the list are evaluated, and only then the appropriate one is picked from it. But this does not stop the recursion from happening even when x == 0. And so the recursion continues into the negative numbers bumping into the memory limit.

... if ... else ... on the other hand will first evaluate the condition following the if keyword, and only evaluate the expression that corresponds to that result.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.