On Oct 22, 4:39 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > 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)
Excuse me, I mistyped your proposed solution. You had xrange(1,x) not xrange(1,x+1). The former only returns correct factorials for x==0 and x==1. Sorry for the confusion. > > >>> 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- Hide quoted text > - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list