Lecture

Implementing Dynamic Programming in Python

Let's explore dynamic programming by examining how to store and reuse subproblem results in Python code.


1. Define the Function and Set Up Memoization

Dynamic programming is the technique of storing and reusing computational results. Memoization is used to achieve this.

Example of Setting Up Memoization
def fibonacci(n, memo={}): if n in memo: return memo[n] # Memoization if n <= 2: return 1 memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo) return memo[n]

2. Recursive Call and Storing Results

The function calculates the (n)-th Fibonacci number and stores it in memo. Stored values are reused.

Example of Recursive Call and Storing Results
if n in memo: return memo[n] if n <= 2: return 1 memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo) return memo[n]

Algorithm Complexity

  1. Time Complexity: O(n)

    • The time complexity of the Fibonacci function using memoization is O(n). Each Fibonacci number is calculated only once, and the calculated value is stored and reused.
  2. Space Complexity: O(n)

    • Due to the additional memory space used for memoization, the space complexity is also O(n). Each computed Fibonacci number is stored in the memo dictionary, so up to n spaces are required to compute the nth number.

Lecture

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result