Calculating factorial
Roger Hansen
rogerha at ifi.uio.no
Wed Dec 6 06:49:44 EST 2000
* Raymond Hettinger
>
> Olli Rajala wrote:
>
> > Hi!
> > I've learned a few time Python and programming. I wrote a function
> > that calculates a factorial of N and I was wondering if it's the best
> > (I think it's not. =) way to do that. I'm glad to hear your comments.
> >
> > def factorial(f):
> > result = 1
> > for number in range(1, f + 1):
> > result = result * number
> > return result
> >
> > print factorial(10)
>
> I like your version just fine. It's simple, clear, and it work's.
> Do consider changing line 2 to: result = 1L so you can
> handle fact(50).
Agree! it's a nice version. But I think the recursive version is even
clearer.
>>> def fact(n):
... if n > 1:
... return n*fact(n-1)
... return 1
...
>>> fact(4)
24
You can change line 3 with
... return long(n)*fact(n-1)
and you have long integers
>>> fact(50)
30414093201713378043612608166064768844377641568960512000000000000L
> If you want to make something hard out of something simple, try:
> def fact(n): return reduce( lambda x,y:x*y, range(2,n+1), 1L )
:-)
R
More information about the Python-list
mailing list