-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathlongest_common_subsequence.py
More file actions
48 lines (38 loc) · 1.21 KB
/
longest_common_subsequence.py
File metadata and controls
48 lines (38 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# longest_common_subsequence.py
# This program finds the Longest Common Subsequence (LCS) between two strings
# using Dynamic Programming and also prints the actual LCS string.
def longest_common_subsequence(X: str, Y: str):
m, n = len(X), len(Y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the dp table
for i in range(1, m + 1):
for j in range(1, n + 1):
if X[i - 1] == Y[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
# Reconstruct the LCS string
i, j = m, n
lcs = []
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
lcs.reverse()
lcs_str = "".join(lcs)
# Print DP table (for visualization)
print("DP Table:")
for row in dp:
print(row)
print(f"\nLength of LCS: {dp[m][n]}")
print(f"LCS String: {lcs_str}")
return dp[m][n], lcs_str
if __name__ == "__main__":
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")
longest_common_subsequence(s1, s2)