Reverse Iteration Through Integers
Mick Krippendorf
mad.mick at gmx.de
Sun Oct 18 21:45:35 EDT 2009
Paul Rubin wrote:
> Yet another way is to use recursion. I'll leave that as an exercise too.
This time with big numbers:
def trampoline(bouncing, *args, **kwargs):
while bouncing:
result, bouncing, args, kwargs = bouncing(*args, **kwargs)
if result:
return result()
def bouncy(function):
return lambda *args, **kwargs:(None, function, args, kwargs)
def land(result=None):
return lambda:result, None, None, None
def reverse(n):
@bouncy
def rev(i=n, j=0, k=0):
if i:
return rev(*divmod(i, 10), k=(j+k)*10)
return land(j + k)
return trampoline(rev)
print reverse(169883903200298309284038223098439430943092816286 ** 123)
Try it without the @bouncy decoration.
Granted, the code looks like a serious case of Haskell envy, but after
recursion and tail call optimization being cryptic was just the logical
consequence ;-)
Mick.
More information about the Python-list
mailing list