"""LCS Problem Statement: Given two sequences, find the length of longest subsequencepresent in both of them. A subsequence is a sequence that appears in the same relativeorder, but not necessarily continuous.Example:"abc", "abg" are subsequences of "abcdefgh"."""def longest_common_subsequence(x: str, y: str):"""Finds the longest common subsequence between two strings. Also returns theThe subsequence foundParameters----------x: str, one of the stringsy: str, the other stringReturns-------L[m][n]: int, the length of the longest subsequence. Also equal to len(seq)Seq: str, the subsequence found>>> longest_common_subsequence("programming", "gaming")(6, 'gaming')>>> longest_common_subsequence("physics", "smartphone")(2, 'ph')>>> longest_common_subsequence("computer", "food")(1, 'o')"""# find the length of stringsassert x is not Noneassert y is not Nonem = len(x)n = len(y)# declaring the array for storing the dp valuesL = [[0] * (n + 1) for _ in range(m + 1)]for i in range(1, m + 1):for j in range(1, n + 1):if x[i - 1] == y[j - 1]:match = 1else:match = 0L[i][j] = max(L[i - 1][j], L[i][j - 1], L[i - 1][j - 1] + match)seq = ""i, j = m, nwhile i > 0 and j > 0:if x[i - 1] == y[j - 1]:match = 1else:match = 0if L[i][j] == L[i - 1][j - 1] + match:if match == 1:seq = x[i - 1] + seqi -= 1j -= 1elif L[i][j] == L[i - 1][j]:i -= 1else:j -= 1return L[m][n], seqif __name__ == "__main__":a = "AGGTAB"b = "GXTXAYB"expected_ln = 4expected_subseq = "GTAB"ln, subseq = longest_common_subsequence(a, b)print("len =", ln, ", sub-sequence =", subseq)import doctestdoctest.testmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。