Avoiding argument checking in recursive calls

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Feb 11 02:58:07 CET 2009


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 :)



I've done this:

def _fact(n):
    if n = 0: return 1
    return _fact(n-1)*n 

def fact(n):
    if n < 0: raise ValueError
    return _fact(n)

but that's ugly. What else can I do?



-- 
Steven



More information about the Python-list mailing list