On Oct 22, 3:38 pm, Paul Rudin <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] writes:
> > On 22 oct, 20:35, Paul Rudin <[EMAIL PROTECTED]> wrote:
>
> >> import operator
> >> def fact(x):
> >>     return reduce(operator.mul, xrange(1,x))
>
> > Maybe:
>
> > import operator
> > def fact(x):
> >     return reduce(operator.mul, xrange(2, x+1), 1)
>
> Or just:
>
> reduce(operator.mul, xrange(1, x), 1)

Nope, still doesn't work:

>>> def fact(x):
        return reduce(operator.mul,xrange(1,x+1),1)

>>> fact(3)
6
>>> fact(2)
2
>>> fact(1)
1
>>> fact(0)
1
>>> fact(-1)
1
>>> fact(-2)
1
>>> fact(-3)
1

fact() should raise an exception if x is negative.

My variant of your original (same as Tim Chase's except the
test for x==1 is not necessary):

>>> def fact(x):
        if x==0:
                return 1
        else:
                return reduce(operator.mul,xrange(1,x+1))

>>> fact(3)
6
>>> fact(2)
2
>>> fact(1)
1
>>> fact(0)
1
>>> fact(-1)

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    fact(-1)
  File "<pyshell#35>", line 5, in fact
    return reduce(operator.mul,xrange(1,x+1))
TypeError: reduce() of empty sequence with no initial value

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to