Re: Iteration for Factorials



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

.



Relevant Pages

  • Re: Whos to blame?
    ... wxPython 2.8.6.1's XRCed tool from a XRC file which in turn is ... def OnInit: ... global __res ... set additional window styles using SetWindowStyleand ...
    (comp.lang.python)
  • Whos to blame?
    ... def OnInit: ... global __res ... Override it for custom setup before the window is created ... set additional window styles using SetWindowStyleand ...
    (comp.lang.python)
  • [ANN] MLTypes: ML-style qualified unions for ruby
    ... def initialize ... @alts = alts ...
    (comp.lang.ruby)
  • Re: [RFC 0/5] sched: Add CPU rate caps
    ... selection and only one scheduler is in force. ... using Stacked Git for the patch development? ... res, so, se = gquilt_utils.run_cmd ... def is_patch_applied: ...
    (Linux-Kernel)
  • Pattern-matching for method arguments in Ruby
    ... def reverse ... you can't say something like "argument 1 should be array with first ... #Empty array means "pattern matched, ... res += r ...
    (comp.lang.ruby)