I am just curios if anyone has done the Self Check questions in “The Three Laws of Recursion”. The book suggests
n <= 1 as the base case for a recursive function to calculate the factorial of a number. I’ve never been a fan of recursion, so perhaps I am nitpicking. But I disagree with the reasoning behind using it instead of
n == 0:
Yes, it is “the most efficient” (if you do insist on using recursion) because you do save yourself one recursive call. (Never mind that recursion in Python is wildly inefficient vs. iteration, to begin with).
But then no, it doesn’t keep “your program from crashing if you try to compute the factorial of a negative number”. You still need to explicitly check if
nis negative (because the factorial of a negative number is undefined). Preferably, you’ll check for negative
nbefore making a recursive call, thus negating the “efficiency advantage” of the proposed base case for negative
I appreciate your thoughts.