File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ # longest_common_subsequence.py
2+ # This program finds the Longest Common Subsequence (LCS) between two strings
3+ # using Dynamic Programming and also prints the actual LCS string.
4+
5+ def longest_common_subsequence (X : str , Y : str ):
6+ m , n = len (X ), len (Y )
7+ dp = [[0 ] * (n + 1 ) for _ in range (m + 1 )]
8+
9+ # Fill the dp table
10+ for i in range (1 , m + 1 ):
11+ for j in range (1 , n + 1 ):
12+ if X [i - 1 ] == Y [j - 1 ]:
13+ dp [i ][j ] = 1 + dp [i - 1 ][j - 1 ]
14+ else :
15+ dp [i ][j ] = max (dp [i - 1 ][j ], dp [i ][j - 1 ])
16+
17+ # Reconstruct the LCS string
18+ i , j = m , n
19+ lcs = []
20+ while i > 0 and j > 0 :
21+ if X [i - 1 ] == Y [j - 1 ]:
22+ lcs .append (X [i - 1 ])
23+ i -= 1
24+ j -= 1
25+ elif dp [i - 1 ][j ] > dp [i ][j - 1 ]:
26+ i -= 1
27+ else :
28+ j -= 1
29+
30+ lcs .reverse ()
31+ lcs_str = '' .join (lcs )
32+
33+ # Print DP table (for visualization)
34+ print ("DP Table:" )
35+ for row in dp :
36+ print (row )
37+
38+ print (f"\n Length of LCS: { dp [m ][n ]} " )
39+ print (f"LCS String: { lcs_str } " )
40+
41+ return dp [m ][n ], lcs_str
42+
43+
44+ if __name__ == "__main__" :
45+ s1 = input ("Enter first string: " )
46+ s2 = input ("Enter second string: " )
47+ longest_common_subsequence (s1 , s2 )
You can’t perform that action at this time.
0 commit comments