Dynamic programming brush question set python code

1 longest common subsequence length

def lcs(x,y,m,n):
    c = [[0]*(n+1)]*(m+1)
    print (len (c), len (c [0]))
    for i in range(m):
        for j in range(n):
            if x[i]==y[j]:
                c[i+1][j+1]=c[i][j]+1
            else:
                c[i+1][j+1]=max(c[i+1][j],c[i][j+1])
    return c[m][n]
x = [1,3,2,5,6]
y = [6,3,2,4,5,7,6]
m,n = 5,7
print(lcs(x,y,m,n))

  Deformation has the shortest edit distance

2 Longest ascending subsequence length

def lis(x,m):
    if m == 0:
        return 0
    c = [1]*m #c[i] is the length of the longest ascending subsequence ending with the i subscript, if m is not 0, then the result is at least 1 
    for i in range(m):
         for j in range (i):
             if x[i]> x[j]:
                c[i] = max(c[j]+1,c[i]) 
    return max(c)
x = [2,1,5,7,10,4]
m = 6
print(lis(x,m))

 

3

Guess you like

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