Advertisement
here2share

# recursive_vs_loops.py

Apr 18th, 2021
992
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.53 KB | None | 0 0
  1. # recursive_vs_loops.py
  2.  
  3. from timeit import timeit
  4.  
  5. setup = """
  6. def fib(n):
  7.     def _fib(prvprv, prv, c):
  8.         if c < 1:
  9.             return prvprv
  10.         return _fib(prv, prvprv + prv, c - 1)
  11.     return _fib(0, 1, n)
  12. """
  13. t = timeit(stmt='fib(35)',
  14.            setup=setup,
  15.            number=100000)
  16. exec(setup)
  17. print fib(35)
  18. print t
  19.  
  20. setup = """
  21. def fib(n):
  22.     a, b = 1, 1
  23.     for _ in xrange(n - 1):
  24.         a, b = b, a + b
  25.     return a
  26. """
  27. t = timeit(stmt='fib(35)',
  28.            setup=setup,
  29.            number=100000)
  30. exec(setup)
  31. print fib(35)
  32. print t
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement