fork download
  1. from itertools import *
  2.  
  3. class Cont(object):
  4. def __init__(self, func, *args):
  5. self.args = args
  6. self.func = func
  7. self.done = False
  8.  
  9. def next(self):
  10. if self.done:
  11. raise StopIteration
  12.  
  13. result = self.func(*self.args)
  14. if isinstance(result, Cont):
  15. self.func = result.func
  16. self.args = result.args
  17. return result
  18. else:
  19. self.done = True
  20. return result
  21. def __iter__(self):
  22. return self
  23.  
  24. def sumto(acc, n):
  25. print "computing %sth sum" % n
  26. if n == 0:
  27. return acc
  28. else:
  29. return Cont(sumto, acc+n, n-1)
  30.  
  31. def fibhelp(prev, cur, n):
  32. print "computing %sth fib" % n
  33. if n == 1:
  34. return prev
  35. else:
  36. return Cont(fibhelp, cur, prev+cur, n-1)
  37.  
  38. def fib(n):
  39. return fibhelp(0, 1, n)
  40.  
  41. list(izip(fib(50), sumto(0, 100)))
Success #stdin #stdout 0.08s 8880KB
stdin
Standard input is empty
stdout
computing 50th fib
computing 100th sum
computing 49th fib
computing 99th sum
computing 48th fib
computing 98th sum
computing 47th fib
computing 97th sum
computing 46th fib
computing 96th sum
computing 45th fib
computing 95th sum
computing 44th fib
computing 94th sum
computing 43th fib
computing 93th sum
computing 42th fib
computing 92th sum
computing 41th fib
computing 91th sum
computing 40th fib
computing 90th sum
computing 39th fib
computing 89th sum
computing 38th fib
computing 88th sum
computing 37th fib
computing 87th sum
computing 36th fib
computing 86th sum
computing 35th fib
computing 85th sum
computing 34th fib
computing 84th sum
computing 33th fib
computing 83th sum
computing 32th fib
computing 82th sum
computing 31th fib
computing 81th sum
computing 30th fib
computing 80th sum
computing 29th fib
computing 79th sum
computing 28th fib
computing 78th sum
computing 27th fib
computing 77th sum
computing 26th fib
computing 76th sum
computing 25th fib
computing 75th sum
computing 24th fib
computing 74th sum
computing 23th fib
computing 73th sum
computing 22th fib
computing 72th sum
computing 21th fib
computing 71th sum
computing 20th fib
computing 70th sum
computing 19th fib
computing 69th sum
computing 18th fib
computing 68th sum
computing 17th fib
computing 67th sum
computing 16th fib
computing 66th sum
computing 15th fib
computing 65th sum
computing 14th fib
computing 64th sum
computing 13th fib
computing 63th sum
computing 12th fib
computing 62th sum
computing 11th fib
computing 61th sum
computing 10th fib
computing 60th sum
computing 9th fib
computing 59th sum
computing 8th fib
computing 58th sum
computing 7th fib
computing 57th sum
computing 6th fib
computing 56th sum
computing 5th fib
computing 55th sum
computing 4th fib
computing 54th sum
computing 3th fib
computing 53th sum
computing 2th fib
computing 52th sum
computing 1th fib
computing 51th sum