Guest User

Fibonacci

a guest
May 12th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. # Functions to calculate nth Fibonacci number
  2. # Memoized and Tabulated versions
  3. from functools import lru_cache
  4. from random import choice
  5. from time import time
  6.  
  7. # top down/memoized version
  8. def td_fib(n, lookup):
  9.     # base case
  10.     if n == 0 or n == 1:
  11.         lookup[n] = n
  12.    
  13.     # if the value was not calculated previously then calculate it
  14.     if lookup[n] is None:
  15.         lookup[n] = td_fib(n-1, lookup) + td_fib(n-2, lookup)
  16.    
  17.     # return the value corresponding to that value of n
  18.     return lookup[n]
  19.  
  20.  
  21. # tabulated/bottom up version
  22. def tab_fib(n):
  23.     # array declation
  24.     f = [0] * (n+1)
  25.    
  26.     # base case assignment
  27.     f[1] = 1
  28.    
  29.     # calculating the fibonacci and storing the values
  30.     for i in range(2, n+1):
  31.         f[i] = f[i-1] + f[i-2]
  32.     return f[n]
  33.  
  34.  
  35. # lru_cache/memoized version
  36. @lru_cache(maxsize=None)
  37. def mem_fib(n):
  38.     if n < 2: return n
  39.     return mem_fib(n - 1) + mem_fib(n - 2)
  40.  
  41.  
  42. def main():
  43.     # n = choice(range(101))
  44.     n = 100
  45.     start = time()
  46.     # declaration of lookup table
  47.     # handles till n = 100
  48.     lookup = [None] * 101
  49.     print(f'Memoized {n} is {td_fib(n, lookup)}')
  50.     print(f'{time() - start} seconds')
  51.     # print([i for i in lookup if i != None])
  52.    
  53.     print('')
  54.     start = time()
  55.     print(f'Tabulated {n} is {tab_fib(n)}')
  56.     print(f'{time() - start} seconds')
  57.    
  58.     print('')
  59.     start = time()
  60.     print(f'LRU Cache {n} is {mem_fib(n)}')
  61.     print(f'{time() - start} seconds')
  62.  
  63.  
  64. if __name__ == '__main__':
  65.     main()
Advertisement
Add Comment
Please, Sign In to add comment