Python:没有获得列表中最长的常见子序列的长度

时间:2015-11-22 02:06:20

标签: python algorithm dynamic-programming

我尝试以最简单的方式在LCS中实现,但我没有得到正确的价值。而不是4我得到。我不确定我的代码有什么问题:

X= ['A','B','C','B','D','A','B']
Y= ['B','D','C','A','B','A','X','Y']

m= len(X)
n= len(Y)
c={}
for i in range(1,m) :
    c[i,0]=0

for j in range(0,n):
    c[0,j]=0

for i in range (1,m):
    for j in range (1,n):
        if X[i]==Y[j]:
            c[i,j]=c[i-1,j-1]+1
        elif c[i-1,j] >= c[i,j-1]:
            c[i,j]=c[i-1,j]
        else:
            c[i,j]=c[i,j-1]


print c[m-1,n-1]
print c

2 个答案:

答案 0 :(得分:1)

看起来您正在使用的单索引可能是您问题的根源。如果我理解正确,您就是在寻找LCS' BCBA'长度为4,但你实际上从未将第一个条目与任何东西进行比较,因此你没有机会匹配' B'这是Y的第一个元素。

我对您的代码做了一些修改,得到了解决方案4:

X = ['A', 'B', 'C', 'B', 'D', 'A', 'B']
Y = ['B', 'D', 'C', 'A', 'B', 'A', 'X', 'Y']

m = len(X)
n = len(Y)
c = {}
for i in range(0, m+1):
    c[i, 0] = 0

for j in range(0, n+1):
    c[0, j] = 0

for i in range(1, m + 1):
    for j in range(1, n + 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])
print c[m, n]

希望这有帮助。

答案 1 :(得分:0)

以下是我用于LCS的实现,它返回(percent_in_common, sequence_in_common)

def longest_common_sequence(a,b):
   from collections import deque

   n1=len(a)
   n2=len(b)
   if not n1:
      if not n2:
         return 100.0, ''
      return 0.0, ''
   if not n2:
      return 0.0, ''
   previous=deque()
   for i in range(n2):
      previous.append((0,''))
   over = (0,'')
   for i in range(n1):
      left = corner = (0,'')
      for j in range(n2):
         over = previous.popleft()
         if a[i] == b[j]:
            this = corner[0] + 1, corner[1]+a[i]
         else:
            this = max(over,left)
         previous.append(this)
         left, corner = this, over
   return round(200.0*this[0]/(n1+n2),2),this[1]