UNB/ CS/ David Bremner/ teaching/ cs3383/ lectures/ 31.0-demos/ lcs2.py
#!/usr/bin/env python3
def lcs(x,y):
  n = len(x); m=len(y)
  c = [ [ 0 for j in range(m+1) ]
        for i in range(n+1) ]
  for i in range(1,n+1):
    for j in range(1,m+1):
      if x[i-1] == y[j-1]:
        c[i][j] = c[i-1][j-1]+1
      else:
        c[i][j] = max(c[i-1][j],c[i][j-1])
  return c

def backtrace(c,x,y,i,j):
  if (i<1) or (j<1):
    return ""
  elif x[i-1] == y[j-1]:
    return backtrace(c,x,y,i-1,j-1)+x[i-1]
  elif (c[i][j-1] > c[i-1][j]):
    return backtrace(c,x,y,i,j-1)
  else:
    return backtrace(c,x,y,i-1,j)

if __name__ == "__main__":

  x = "TOURLAKE"
  y = "RATEBACKER"
  n = len(x)
  m = len(y)

  c = lcs(x,y)

  print("lcs length=",c[n][m])
  print("lcs=",backtrace(c,x,y,n,m))