Advertisement
Guest User

Longest Common Sequence

a guest
Apr 28th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1.  
  2. # Two functions to identify the longest common sequence between two strings
  3.  
  4.  
  5. def LCS1(x, y) :
  6.  
  7.     m = len(x)
  8.     n = len(y)
  9.  
  10.     longestMatch = ''           # the longest common sequence found (yet)
  11.  
  12.     for d in xrange(1-n, m) :   # we browse the matrix intersection of x and y along its diagonals : d = i-j
  13.  
  14.         iMin = max(0, d)
  15.         iMax = min(m, n+d)
  16.         match = ''              # any common sequence currently going on
  17.  
  18.         for i in xrange(iMin, iMax) :
  19.             j = i-d
  20.             if x[i] == y[j] :
  21.                 match += x[i]                           # if a common sequence is going on we fill up 'match'
  22.             else :
  23.                 if len(match) > len(longestMatch) :     # otherwise we check if a long enough common sequence just ended
  24.                     longestMatch = match
  25.                 match = ''                              # and we reset 'match'
  26.  
  27.         if len(match) > len(longestMatch) :
  28.             longestMatch = match                        # in case there was a common sequence at the end of this diagonal
  29.  
  30.     return longestMatch
  31.  
  32.  
  33. def LCS2(x,y) :
  34.  
  35.     m = len(x)
  36.     n = len(y)
  37.  
  38.     longestMatch = ''           # the longest common sequence found (yet)
  39.  
  40.     for i in xrange(m) :
  41.         for j in xrange(n) :    # we browse the matrix intersection of x and y along its rows and columns
  42.             k = 0
  43.             match = ''
  44.             while i+k < m and j+k < n and x[i+k] == y[j+k] :    # from our current position we follow the diagonal to try and find a common sequence, if any
  45.                 match += x[i+k]
  46.                 k += 1
  47.             if k > len(longestMatch) :
  48.                 longestMatch = match
  49.  
  50.     return longestMatch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement