LCS Dynamic Programming Table (Python)
Compute the longest common subsequence of two strings using dynamic programming with full table reconstruction.
Code
def longest_common_subseq(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
i, j = m, n
result = []
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
result.insert(0, a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] > dp[i][j - 1]:
i -= 1
else:
j -= 1
return "".join(result)Inside the snippet
The working surface is the function longest_common_subseq — everything else is wiring.
Repetition is confined to for i in range(1, m + 1) — the rest of the file is straight-line.
Putting it to use
Signature: def longest_common_subseq(a, b)
longest_common_subseq is what another module would consume; nothing else here is load-bearing for callers.
Core lines
elif dp[i - 1][j] > dp[i][j - 1]:
i -= 1
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `longest_common_subseq` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.