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
-
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.
-
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
memodictionary, so up to n spaces are required to compute the nth number.
- Due to the additional memory space used for memoization, the space complexity is also O(n). Each computed Fibonacci number is stored in the
Lessons in this chapter · Practical Python Algorithms
- 1. Advanced Python Algorithms
- 2. What is a Recursive Call?
- 3. Implementing Fibonacci Sequence with Recursive Function
- 4. Fill-in-the-blank quiz
- 5. Coding Quiz - Fibonacci Sequence
- 6. Dynamic Programming and Divide and Conquer
- 7. Implementing Dynamic Programming in Python
- 8. Multiple-choice quiz
- 9. Coding Quiz - Make One
- 10. What is Merge Sort?
- 11. Implementing Merge Sort
- 12. Multiple-choice quiz
- 13. Coding Quiz - Sort a List Using Merge Sort
- 14. What is Quick Sort?
- 15. Implementing Quick Sort in Python
- 16. Multiple-choice quiz
- 17. Coding Quiz - Sort a List Using Quick Sort
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help