Steven D'Aprano wrote:
I sometimes write recursive functions like this simple factorial:
def fact(n):
    if n < 0: raise ValueError
    if n = 0: return 1
return fact(n-1)*n At the risk of premature optimization, I wonder if there is an idiom for avoiding the unnecessary test for n <= 0 in the subsequent recursive calls? For the sake of the argument, let's pretend the test is expensive and I have a good reason for wanting to avoid it on subsequent calls :)
How about:

     def fact(n):
         if n < 2:
             if n < 0:
                 raise ValueError
             return 1
         return fact(n - 1) * n

But really, iteration is the solution to this, and avoiding the
right answer is a mistake.  I couldn't resist fixing your test
so you do one less layer of recursion.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to