Iteration for Factorials
J. Clifford Dyer
jcd at sdf.lonestar.org
Tue Oct 30 14:52:42 EDT 2007
On Tue, Oct 30, 2007 at 11:37:57AM -0700, mensanator at aol.com wrote regarding Re: Iteration for Factorials:
>
> 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?
>
I can't speak for everyone, but my excuses are as follows:
* I haven't studied math or done math-heavy work in 8 years.
* I'm not at my home computer, and most of the thread (wherein, I now recall, that particular rule was specified) is downloaded to my home computer, so I was working from my feeble memory.
* I didn't care enough to google for it.
That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem
More information about the Python-list
mailing list