Re: Iteration for Factorials



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


.



Relevant Pages

  • Re: infinite loop
    ... > def function_a: ... > iteration = True ... > RuntimeError: maximum recursion depth exceeded ... What should I do for having an infinite loop? ...
    (comp.lang.python)
  • Re: Question - What is a faster alternative to recursion?
    ... iteration is 10000000000 times faster than recursion. ... > def rec: ... 1000 loops, best of 3: ...
    (comp.lang.python)
  • Re: infinite loop
    ... >> def main: ... >> RuntimeError: maximum recursion depth exceeded ... What should I do for having an infinite loop? ... while iteration: ...
    (comp.lang.python)
  • Re: Characters contain themselves?
    ... iterating on a string or on another kind of "list".... ... except:# if no iteration is possible ... and so triggers an infinite descent of recursion. ... def copier: ...
    (comp.lang.python)
  • Re: Software bugs arent inevitable
    ... > for loops (use recursion instead). ... resource-requirement differences between iteration and recursion can be ... def fibr: ... "Recursive version of Fibonacci sequence." ...
    (comp.lang.python)