from itertools import *
class Cont(object):
def __init__(self, func, *args):
self.args = args
self.func = func
self.done = False
def next(self):
if self.done:
raise StopIteration
result = self.func(*self.args)
if isinstance(result, Cont):
self.func = result.func
self.args = result.args
return result
else:
self.done = True
return result
def __iter__(self):
return self
def sumto(acc, n):
print "computing %sth sum" % n
if n == 0:
return acc
else:
return Cont(sumto, acc+n, n-1)
def fibhelp(prev, cur, n):
print "computing %sth fib" % n
if n == 1:
return prev
else:
return Cont(fibhelp, cur, prev+cur, n-1)
def fib(n):
return fibhelp(0, 1, n)
list(izip(fib(50), sumto(0, 100)))
ZnJvbSBpdGVydG9vbHMgaW1wb3J0ICoKIApjbGFzcyBDb250KG9iamVjdCk6CiAgICBkZWYgX19pbml0X18oc2VsZiwgZnVuYywgKmFyZ3MpOgogICAgICAgIHNlbGYuYXJncyA9IGFyZ3MKICAgICAgICBzZWxmLmZ1bmMgPSBmdW5jCiAgICAgICAgc2VsZi5kb25lID0gRmFsc2UKICAgIAogICAgZGVmIG5leHQoc2VsZik6CiAgICAgICAgaWYgc2VsZi5kb25lOgogICAgICAgICAgICByYWlzZSBTdG9wSXRlcmF0aW9uCiAKICAgICAgICByZXN1bHQgPSBzZWxmLmZ1bmMoKnNlbGYuYXJncykKICAgICAgICBpZiBpc2luc3RhbmNlKHJlc3VsdCwgQ29udCk6CiAgICAgICAgICAgIHNlbGYuZnVuYyA9IHJlc3VsdC5mdW5jCiAgICAgICAgICAgIHNlbGYuYXJncyA9IHJlc3VsdC5hcmdzCiAgICAgICAgICAgIHJldHVybiByZXN1bHQKICAgICAgICBlbHNlOgogICAgICAgICAgICBzZWxmLmRvbmUgPSBUcnVlCiAgICAgICAgICAgIHJldHVybiByZXN1bHQKICAgIGRlZiBfX2l0ZXJfXyhzZWxmKToKICAgICAgICByZXR1cm4gc2VsZgogCmRlZiBzdW10byhhY2MsIG4pOgogICAgcHJpbnQgImNvbXB1dGluZyAlc3RoIHN1bSIgJSBuCiAgICBpZiBuID09IDA6CiAgICAgICAgcmV0dXJuIGFjYwogICAgZWxzZToKICAgICAgICByZXR1cm4gQ29udChzdW10bywgYWNjK24sIG4tMSkKICAgICAgICAKZGVmIGZpYmhlbHAocHJldiwgY3VyLCBuKToKICAgIHByaW50ICJjb21wdXRpbmcgJXN0aCBmaWIiICUgbgogICAgaWYgbiA9PSAxOgogICAgICAgIHJldHVybiBwcmV2CiAgICBlbHNlOgogICAgICAgIHJldHVybiBDb250KGZpYmhlbHAsIGN1ciwgcHJlditjdXIsIG4tMSkKIApkZWYgZmliKG4pOgogICAgcmV0dXJuIGZpYmhlbHAoMCwgMSwgbikKIApsaXN0KGl6aXAoZmliKDUwKSwgc3VtdG8oMCwgMTAwKSkp