Dynamic Programming in Python
Dynamic programming is a powerful technique for solving complex problems by breaking them down into smaller sub-problems, solving each sub-problem only once, and storing the solutions to sub-problems to avoid redundant computation.
Table of Contents
- Fibonacci Series
- Longest Common Subsequence (LCS)
- 0/1 Knapsack Problem
- Shortest Path Problem (Dijkstra's Algorithm)
- Matrix Chain Multiplication
Fibonacci Series
The Fibonacci series is a classic example of dynamic programming. The problem statement is:
Given a number n, find the n-th Fibonacci number.
Naive Recursive Solution ( Exponential Time Complexity: O(2^n) )
def fibonacci_recursive(n):
if n <= 1:
return n
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
Dynamic Programming Solution ( Linear Time Complexity: O(n) )
def fibonacci_dp(n):
fib = [0] * (n + 1)
fib[1] = 1
for i in range(2, n + 1):
fib[i] = fib[i-1] + fib[i-2]
return fib[n]
Example Usage
print(fibonacci_dp(10)) # Output: 55
Longest Common Subsequence (LCS)
Given two sequences X and Y, find the longest common subsequence.
Problem Statement
- Input: Two sequences
X = [x1, x2, ..., xm] and Y = [y1, y2, ..., yn]
- Output: The longest common subsequence
Z = [z1, z2, ..., zk]
Dynamic Programming Solution ( Time Complexity: O(m*n) )
def lcs(X, Y):
m, n = len(X), len(Y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if X[i-1] == Y[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
# Reconstruct the LCS
lcs = []
i, j = m, n
while i > 0 and j > 0:
if X[i-1] == Y[j-1]:
lcs.append(X[i-1])
i -= 1
j -= 1
elif dp[i-1][j] > dp[i][j-1]:
i -= 1
else:
j -= 1
return "".join(reversed(lcs))
# Example Usage
X = "AGGTAB"
Y = "GXTXAYB"
print(lcs(X, Y)) # Output: "GTAB"
0/1 Knapsack Problem
Given a set of items, each with a weight and a value, determine the subset of items to include in a knapsack of limited capacity.
Problem Statement
- Input:
weights = [w1, w2, ..., wn]
values = [v1, v2, ..., vn]
capacity = W
- Output: The maximum value that can be put in the knapsack
Dynamic Programming Solution ( Time Complexity: O(n*W) )
def knapsack(weights, values, capacity):
n = len(values)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, capacity + 1):
if weights[i-1] <= w:
dp[i][w] = max(values[i-1] + dp[i-1][w-weights[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
return dp[n][capacity]
# Example Usage
weights = [2, 3, 4, 5]
values = [10, 20, 30, 40]
capacity = 7
print(knapsack(weights, values, capacity)) # Output: 50
Shortest Path Problem (Dijkstra's Algorithm)
Given a graph with non-negative edge weights, find the shortest path from a source node to all other nodes.
Problem Statement
- Input: A graph
G = (V, E) with edge weights w(u, v)
- Output: The shortest distance from the source node
s to all other nodes
Dynamic Programming Solution ( Time Complexity: O(|E| + |V|log|V|) )
import heapq
def dijkstra(graph, source):
distances = {node: float('inf') for node in graph}
distances[source] = 0
pq = [(0, source)]
while pq:
current_distance, current_node = heapq.heappop(pq)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
# Example Usage
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
source = 'A'
print(dijkstra(graph, source)) # Output: {'A': 0, 'B': 1, 'C': 3, 'D': 4}
Matrix Chain Multiplication
Given a sequence of matrices, find the most efficient way to multiply them.
Problem Statement
- Input: A sequence of matrices
A1, A2, ..., An with dimensions p0 x p1, p1 x p2, ..., pn-1 x pn
- Output: The minimum number of scalar multiplications required to compute the product
A1*A2*...*An
Dynamic Programming Solution ( Time Complexity: O(n^3) )
def matrix_chain_order(p):
n = len(p) - 1
m = [[0] * n for _ in range(n)]
s = [[0] * n for _ in range(n)]
for chain_length in range(2, n + 1):
for i in range(n - chain_length + 1):
j = i + chain_length - 1
m[i][j] = float('inf')
for k in range(i, j):
q = m[i][k] + m[k+1][j] + p[i]*p[k+1]*p[j+1]
if q < m[i][j]:
m[i][j] = q
s[i][j] = k
return m, s
def print_optimal_parens(s, i, j):
if i == j:
print(f"A{i+1}", end="")
else:
print("(", end="")
print_optimal_parens(s, i, s[i][j])
print_optimal_parens(s, s[i][j] + 1, j)
print(")", end="")
# Example Usage
p = [30, 35, 15, 5, 10, 20, 25]
m, s = matrix_chain_order(p)
print("Minimum number of scalar multiplications:", m[0][5])
print("Optimal parenthesization: ", end="")
print_optimal_parens(s, 0, 5)
These examples demonstrate the power of dynamic programming in solving complex problems efficiently. By breaking down problems into smaller sub-problems, solving each sub-problem only once, and storing the solutions to sub-problems, dynamic programming can reduce the time complexity of problems from exponential to polynomial or even linear.
Happy coding!