Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. import datetime
  2. from contextlib import contextmanager
  3.  
  4. def slowfib(n):
  5. return n if n<2 else slowfib(n-1) + slowfib(n-2)
  6.  
  7. def fastfib(n):
  8. a, b = 0, 1
  9. for i in range(0, n):
  10. a, b = b, a + b
  11. return a
  12.  
  13. def memo(f):
  14. b4 = {}
  15. def helper(x):
  16. if x not in b4:
  17. b4[x] = f(x)
  18. return b4[x]
  19. return helper
  20.  
  21. @memo
  22. def fib(n):
  23. return n if n<2 else fib(n-1) + fib(n-2)
  24.  
  25. @contextmanager
  26. def watch():
  27. a = datetime.datetime.now()
  28. yield
  29. b = datetime.datetime.now()
  30. print("time= %s micros" % (b-a).microseconds)
  31.  
  32. for i in range(1,100):
  33. print("")
  34. with watch(): print("slowfib",i,slowfib(i),end=" ")
  35. with watch(): print("fastfib",i,fastfib(i),end=" ")
  36. with watch(): print("memofib",i,fib(i),end=" ")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement