Avoiding argument checking in recursive calls
Jervis Whitley
jervisau at gmail.com
Tue Feb 10 21:48:09 EST 2009
> 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?
>
>
Hello, an idea is optional keyword arguments.
def fact(n, check=False):
if not check:
if n < 0: raise ValueError
if n == 0: return 1
return fact(n - 1, check=True) * n
essentially hiding an expensive check with a cheap one. It saves you
duplicating code in a separate function like in your example.
More information about the Python-list
mailing list