我已经编写了这些函数(它们是有效的)来查找两个字符串的最长公共子序列。在def lcs_grid(xs, ys):
grid = defaultdict(lambda: defaultdict(lambda: (0,"")))
for i,x in enumerate(xs):
for j,y in enumerate(ys):
if x == y:
grid[i][j] = (grid[i-1][j-1][0]+1,'\\')
else:
if grid[i-1][j][0] > grid[i][j-1][0]:
grid[i][j] = (grid[i-1][j][0],'
else:
grid[i][j] = (grid[i][j-1][0],'^')
return grid
def lcs(xs,ys):
grid = lcs_grid(xs,ys)
i, j = len(xs) - 1, len(ys) - 1
best = []
length,move = grid[i][j]
while length:
if move == '\\':
best.append(xs[i])
i -= 1
j -= 1
elif move == '^':
j -= 1
elif move == '
i -= 1
length,move = grid[i][j]
best.reverse()
return best
有人提议修改函数s.t.他们可以打印三个字符串中最长的公共子序列吗?一、 函数调用是:lcs(str1, str2, str3)
到目前为止,我用'reduce'-语句来管理它,但是我希望有一个函数,它可以真正打印出没有'reduce'语句的子序列。在