fork(3) download
  1. #That's a band-aid though. Instead of going into these crazy-deep (at least for Python, it would be another story in LISP or Haskell) recursions, you should rewrite your algorithm to an iterative one. If it is tail-recursive, a loop will suffice. In other cases, you can simply keep a list of tasks. For example, instead of
  2.  
  3. def fib(x):
  4. if x < 2: return x
  5. return fib(x-1) + fib(x-2)
  6.  
  7. #write
  8.  
  9. import collections
  10. def fib_iter(x):
  11. tasks = collections.deque([x])
  12. res = 0
  13. while tasks:
  14. v = tasks.pop()
  15. if v < 2:
  16. res += v
  17. continue
  18. tasks.append(v-1)
  19. tasks.append(v-2)
  20. return res
  21.  
  22. for i in range(10):
  23. assert fib_iter(i) == fib(i), 'Got %r, expected %r for fib(%d)' % (fib_iter(i), fib(i), i)
Success #stdin #stdout 0.15s 10264KB
stdin
Standard input is empty
stdout
Standard output is empty