Python implements the longest common subsequence dynamic programming problem

In python, I wrote a dynamic programming method to find the longest common subsequence of two sequences. If there is any problem with the code, please give me some pointers.

 
  
# -*- coding: utf-8 -*-
#author:Huangyuliang
# Longest common subsequence problem
# Find the longest common subsequence of a,b sequence
import numpy as np

def lcs_len(a,b):
    n = len (a)
    m = only (b)
    p = n+1
    q = m+1
    c = np.zeros((p,q))
    val = c.copy()
    for i in range(1,p):
        for j in range(1,q):
            if a[i-1] == b[j-1]:
                c[i,j] = c[i-1,j-1] + 1
                val[i,j] = 0 # in the upper left corner
            elif c[i-1,j] >= c[i,j-1]:
                c[i,j] = c[i-1,j]
                val[i,j] = 1 # above
            else:
                c[i,j] = c[i,j-1]
                val[i,j] = 2 # on the left
    k = int(c[n,m]) # k is equal to the number of elements of the longest common subsequence
    print "k =",k
    G = range(k+1) # G is used to store the longest common subsequence
    while k>0:
        if val[n,m]==1:
            n-=1
        elif val[n,m]==2:
            m-=1
        else:
            G[k] = a[n-1]
            k-=1
            n-=1
            m-=1
    return G[1:]

a,b = [1,2,3,5,7,8,9],[1,2,3,4,5,9]
h = lcs_len (a, b)
print h
Output result:
k = 5
h = [1,2,3,5,9]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325548207&siteId=291194637
Recommended