Advertisement
ThihaNyein

Recursive Vs Dynamic Programming

Mar 1st, 2022 (edited)
1,927
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None | 0 0
  1. from time import time
  2.  
  3. def run(func,arg):
  4.     """
  5.    Calculate the execution time
  6.    """
  7.     start = time()
  8.     ans = func(arg)
  9.     end = time()
  10.    
  11.     long = (end-start)*1000
  12.    
  13.     print(f"{func.__name__}({arg}) take {long} ms to execute")
  14.     print(f"Output: {ans}")
  15.    
  16. # Recursive Function
  17. def re_f(n):
  18.     if n == 0 or n == 1:
  19.         return 1
  20.     else:
  21.         return re_f(n-1) + re_f(n-2)
  22.  
  23. # Dynamic Programming
  24. def dyn_f(n, dic = {}):
  25.      if n in dic:
  26.          return dic[n]
  27.      if n == 0 or n == 1:
  28.         return 1
  29.      else:
  30.         dic[n] = dyn_f(n-1,) + dyn_f(n-2)
  31.         return dic[n]
  32.  
  33. run(dyn_f,30)
  34. run(re_f,30)
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement