On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re:
Iteration for Factorials:
>
> Py-Fun wrote:
> > I'm stuck trying to write a function that generates a factorial of a
> > number using iteration and not recursion. Any simple ideas would be
> > appreciated.
> >
>
> fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
>
OK. Now I've been sucked in. How about this:
def fact(x):
def f(x):
if int(x) != x:
raise ValueError
elif x > 1:
return f(x-1) ** x
elif x == 1:
return 10
else:
raise ValueError
return len(str(f(x))) -1
The great part about this recursive solution is that you don't have to worry
about the stack limit because performance degrades so quickly on the conversion
to string! fact(8) takes a little less than a second, fact(9) takes about a
minute, and fact(10) takes more time than I had patience to wait for!
Cheers,
Cliff
--
http://mail.python.org/mailman/listinfo/python-list