I am trying to implement a count variable in the function below using dynamic programming specifically memoization. The method calculates the value in a Fibonacci sequence at a given index. I cannot figure out why the count (in this case the number of times this program executes) is not returned.
def fibonacci_memoized():
cached = {}
count = [0]
def fib(n):
count[0] += 1
if n in cached:
return cached[n]
elif n < 2:
cached[n] = n
return n
elif n >= 2:
cached[n] = fib(n-1) + fib(n-2)
return cached[n]
return fib, count[0]
fib_calculation, c = fibonacci_memoized()
print("Memoized recursive Fibonacci sequence solution:", fib_calculation(given_index), "Execution:", c)
Output:
Memoized recursive Fibonacci sequence solution: 13 Execution: 0
Additionally, is this a good way to implement a method using dynamic programming in python, can this code be made better?
count[0]instead ofcount