Iteration for Factorials
mensanator at aol.com
mensanator at aol.com
Tue Oct 30 14:37:57 EDT 2007
On Oct 30, 10:25 am, "J. Clifford Dyer" <j... at sdf.lonestar.org> wrote:
> 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!
And the not-so-great part is that it raises an exception
on fact(0) which makes it utterly useless for calculating
combinations of m things taken n at a time: m!/n!*(m-n)!
Why is it that no one seems able to get this right?
>
> Cheers,
> Cliff
More information about the Python-list
mailing list