RosettaCodeData/Task/Longest-common-subsequence/Python/longest-common-subsequence-3.py

19 lines
594 B
Python
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
def lcs(a, b):
2019-09-12 10:33:56 -07:00
# generate matrix of length of longest common subsequence for substrings of both words
lengths = [[0] * (len(b)+1) for _ in range(len(a)+1)]
2013-04-10 21:29:02 -07:00
for i, x in enumerate(a):
for j, y in enumerate(b):
if x == y:
lengths[i+1][j+1] = lengths[i][j] + 1
else:
2016-12-05 22:15:40 +01:00
lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1])
2019-09-12 10:33:56 -07:00
# read a substring from the matrix
result = ''
j = len(b)
for i in range(1, len(a)+1):
if lengths[i][j] != lengths[i-1][j]:
result += a[i-1]
2013-04-10 21:29:02 -07:00
return result