here2share

# recursive_vs_loops.py

Apr 18th, 2021
546
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×