Avoiding argument checking in recursive calls

Scott David Daniels Scott.Daniels at Acm.Org
Wed Feb 11 01:57:18 EST 2009


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.Daniels at Acm.Org



More information about the Python-list mailing list