Iteration for Factorials
mensanator at aol.com
mensanator at aol.com
Mon Oct 22 17:39:48 EDT 2007
On Oct 22, 3:38 pm, Paul Rudin <paul.nos... at rudin.co.uk> wrote:
> tokl... at gmail.com writes:
> > On 22 oct, 20:35, Paul Rudin <paul.nos... at rudin.co.uk> 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
More information about the Python-list
mailing list