This example describes the Python longest common substring algorithm. Share to everyone for your reference. as follows:
#!/usr/bin/env Python # Find an LCS (longest Common subsequence). # *public domain* def find_lcs_len (S1, s2): M = [[0 for X in S2] for y in S1] for P1 in range (len (S1)): for P2 in range (len (s2)): if S1[P1] = S2[p2]: If p1 = 0 or P2 = = 0:m[p1][p2] = 1 ELSE:M[P1][P2] = M[p1-1][p2-1]+1 elif M[P1-1][P2] < m[p1][p2-1]: m[p1][p2] = m[p1][p2-1] Else: # m[p1][p2-1] < M[P1-1][P2] M[P1][P2] = M[p1-1][p2] return m[-1][-1] def find_lcs (S1, S2): # length Table:every element
is set to zero.
m = [[0 for X-S2] for y-S1] # direction table:1st bit for P1, 2nd bit for P2.
d = [[None for X in S2] for y in S1] # we don ' t have to care about the Boundery check.
# A negative index always gives an intact zero. For P1 in range (len (S1)): For P2 in range (len (s2): if S1[P1] = S2[p2]: If p1 = 0 or P2 = 0:m[p1][p2 ] = 1 Else:m[p1][p2] = m[p1-1][p2-1]+1 D[P1][P2] = 3 # 11:DECR. P1 and P2 elif m[p1-1][p2] < m[p1][p2-1]: m[p1][p2] = m[p1][p2-1] d[p1][p2] = 2 # 10:DECR. P2 only else: # M[p1][p2-1] < M[P1-1][P2] M[P1][P2] = m[p1-1][p2] d[p1][p2] = 1 # 01:DECR.
P1 only (p1, p2) = (len (S1)-1, Len (S2)-1) # Now we traverse the ' table in ' reverse order. s = [] while 1:print p1,p2 C = d[p1][p2] if c = = 3:s.append (S1[P1]) if not ((P1 or P2) and M[P1][P2]): Bre AK if C & 2:p2 = 1 if c & 1:p1-= 1 s.reverse () return '. Join (s) if __name__ = = ' __main__ ': print Find_lcs (' Abcoisjf ', ' Axbaoeijf ') print Find_lcs_len (' abcoisjf ', ' AXBAOEIJF ')
I hope this article will help you with your Python programming.