Here is how to calculate fibonacci with dynamic programming caching.
Run the program here: https://repl.it/@VinitKhandelwal/fibonacci-dynamic-programming
OUTPUT
Fibonacci without caching 832040
Calculated 2692537 times
Fibonacci without caching 832040
Calculated 32 times
Run the program here: https://repl.it/@VinitKhandelwal/fibonacci-dynamic-programming
cal = 0
def slowFibonacci(n):
  global cal
  cal += 1
  if n<2:
    return n
  return slowFibonacci(n-1) + slowFibonacci(n-2)
cal2 = 0
cache = {}
def fastFibonacci(n):
  global cache, cal2
  if n in cache:
    return cache[n]
  else:
    cal2 += 1
    if n<2:
      return n
    cache[n] = fastFibonacci(n-1) + fastFibonacci(n-2)
    return cache[n]
print(f"Fibonacci without caching {slowFibonacci(30)}")
print(f"Calculated {cal} times")
print(f"Fibonacci without caching {fastFibonacci(30)}")
print(f"Calculated {cal2} times")
Fibonacci without caching 832040
Calculated 2692537 times
Fibonacci without caching 832040
Calculated 32 times
Comments
Post a Comment