Re: Iteration for Factorials
- From: Marco Mariani <marco@xxxxxxxxxxxxxx>
- Date: Mon, 22 Oct 2007 17:31:04 +0200
From the cookbook, this time.
It satisfies the requirements nicely ;)
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
def tail_recursion(g):
'''
Version of tail_recursion decorator using no stack-frame inspection.
'''
loc_vars ={"in_loop":False,"cnt":0}
def result(*args, **kwd):
loc_vars["cnt"]+=1
if not loc_vars["in_loop"]:
loc_vars["in_loop"] = True
while 1:
tc = g(*args,**kwd)
try:
qual, args, kwd = tc
if qual == 'continue':
continue
except (TypeError, ValueError):
loc_vars["in_loop"] = False
return tc
else:
if loc_vars["cnt"]%2==0:
return ('continue',args, kwd)
else:
return g(*args,**kwd)
return result
@tail_recursion
def factorial(n, acc=1):
"calculate a factorial"
if n == 0:
return acc
res = factorial(n-1, n*acc)
return res
.
- Follow-Ups:
- Re: Iteration for Factorials
- From: Tim Golden
- 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
- Re: Iteration for Factorials
- From: Ant
- Iteration for Factorials
- Prev by Date: Re: pydoc script.py vs. pydoc scriptpy
- 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
|