Guest User

Untitled

a guest
Jun 17th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. # recursion
  2. def fib(n):
  3. if n <= 1:
  4. return n
  5.  
  6. return fib(n-1) + fib(n-2)
  7.  
  8. # recursion with memoization
  9. def fib_memo(n, lookup=None):
  10. """
  11. Memoization will continue to take on the overheard of function invocations
  12. """
  13. if lookup is None:
  14. lookup = [None]*(n+1)
  15.  
  16. if n is 0 or n is 1:
  17. lookup[n] = n
  18.  
  19. if lookup[n] is None:
  20. lookup[n] = fib_memo(n-1, lookup) + fib_memo(n-2, lookup)
  21.  
  22. return lookup[n]
  23.  
  24. # iterative DP
  25. def fib_dyn(n):
  26. """
  27. Utilizes tabulation
  28. - Note that the difference between the memoization solution is the absence of repeated function calls and its overhead
  29. """
  30. table = [0] * (n+1)
  31. table[1] = 1
  32.  
  33. for i in range(2, n+1):
  34. table[i] = table[i-1] + table[i-2]
  35.  
  36. return table[n]
Add Comment
Please, Sign In to add comment