求最长公共子序列
# -- coding: utf-8 --
import os
import glob
import sys
import cv2
import shutil
import numpy as np
import random
def lcs(X, Y):
m, n = len(X), len(Y)
L = [[0 for x in range(n + 1)] for x in range(m + 1)]
# build dp
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
index = L[m][n]
# backtrace
i, j = m, n
match = []
while i > 0 and j > 0:
if X[i - 1] == Y[j - 1]:
match.append((i-1, j-1))
i -= 1
j -= 1
index -= 1
elif L[i - 1][j] > L[i][j - 1]:
i -= 1
else:
j -= 1
match.reverse()
# 求common
common = []
for i, j in match:
common.append(X[i])
# 求union
union = []
newX = []
newY = []
wild = "#"
anchors = [(-1, -1)]
for pair in match:
anchors.append(pair)
anchors.append((m, n))
for i in range(1, len(anchors)):
xs, ys = anchors[i-1]
xs += 1
ys += 1
xe, ye = anchors[i]
for k in range(xs, xe):
union.append(X[k])
newX.append(X[k])
newY.append(wild)
for k in range(ys, ye):
union.append(Y[k])
newX.append(wild)
newY.append(Y[k])
if i != len(anchors)-1:
union.append(X[xe])
newX.append(X[xe])
newY.append(X[xe])
return match, common, union, newX, newY
def sample_sequence(full, r=0.75):
new = []
for i in full:
if random.random() < r:
new.append(i)
return new
if __name__ == '__main__':
# Driver program
real = ['7-8', '3-4', '12-2', '19-17', '12-16', '14-19', '2-5', '12-18', '9-7', '17-3', '15-15', '13-13', '14-7', '4-17', '9-14', '5-4', '6-8', '1-5', '18-14', '12-20']
s1 = sample_sequence(real)
s2 = sample_sequence(real)
match, common, union, newX, newY = lcs(s1, s2)
for i in range(len(union)):
print(newX[i].ljust(8, ' '), newY[i].ljust(8, ' '), union[i].ljust(8, ' '))