Avoiding argument checking in recursive calls
afriere at yahoo.co.uk
afriere at yahoo.co.uk
Tue Feb 10 23:42:47 EST 2009
On Feb 11, 1:48 pm, Jervis Whitley <jervi... at gmail.com> wrote:
> 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.
Given the original read:
def fact(n):
if n < 0: raise ValueError
if n = 0: return 1
return fact(n-1)*n
You've merely replaced the 'test n<0' with 'not check' at the expense
of an additional parameter that has to be passed each time (and the
additional test 'n<0' for the first iteration).
More information about the Python-list
mailing list