This article describes the python's longest common substring algorithm. Share to everyone for your reference. Specific as follows:
#!/usr/bin/env Python # Find an LCS (longest Common subsequence). # *public domain* def find_lcs_len (S1, s2): M = [[0 for X ' 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][p 2-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 in S2] for y in 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 a 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]): Break I F C & 2:P2-= 1 if C & 1:p1-= 1 s.reverse () return '. Join (s) if __name__ = = ' __main__ ': Print Find_lcs (' AB Coisjf ', ' Axbaoeijf ') print Find_lcs_len (' abcoisjf ', ' AXBAOEIJF ')
Hopefully this article will help you with Python programming.