Skip to content
Advertisement

Returning value in a nested function when using memoization

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.

JavaScript

Output:

JavaScript

Additionally, is this a good way to implement a method using dynamic programming in python, can this code be made better?

Advertisement

Answer

The issue is that you are returning count[0], which is an integer. This doesn’t get modified, the reference to count[0] does. So return count instead:

JavaScript

And to show the memoization works, we can run the loop a second time:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement