Re: Iteration for Factorials
- From: Ant <antroy@xxxxxxxxx>
- Date: Mon, 22 Oct 2007 07:45:48 -0700
On Oct 22, 1:26 pm, Py-Fun <lorna.bu...@xxxxxxxxx> 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.
The following simple adder functions should give you an idea of how
recursion can be recast as iteration:
def acc(i):
'''i should be a positive integer'''
if i > 0:
return i + acc(i - 1)
return 0
print "acc", acc(9)
def itt(i):
'''i should be a positive integer'''
out = 0
while i > 0:
out += i
i = i - 1
return out
print "itt", itt(9)
...
Is it a "factorial" though?
Er, no. And neither is mine. You may want to google for the definition
of factorial! Here's a hint:
reduce(operator.mul, range(1, i + 1))
--
Anthony Roy
.
- Follow-Ups:
- Re: Iteration for Factorials
- From: Roberto Bonvallet
- Re: Iteration for Factorials
- From: Marco Mariani
- Re: Iteration for Factorials
- References:
- Iteration for Factorials
- From: Py-Fun
- Re: Iteration for Factorials
- From: Diez B. Roggisch
- Re: Iteration for Factorials
- From: Py-Fun
- Re: Iteration for Factorials
- From: Marco Mariani
- Re: Iteration for Factorials
- From: Py-Fun
- Iteration for Factorials
- Prev by Date: Re: Check File Change Every 10 Seconds
- Next by Date: RE: Check File Change Every 10 Seconds
- Previous by thread: Re: Iteration for Factorials
- Next by thread: Re: Iteration for Factorials
- Index(es):
Relevant Pages
|