Created
June 28, 2017 09:33
-
-
Save aqzlpm11/272e4ebcd060996fdf508ee2f434cea5 to your computer and use it in GitHub Desktop.
python: Longest common subsequence (LCS) algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import lru_cache | |
@lru_cache(maxsize=2**20) | |
def LCS(a, b): | |
""" Longest common subsequence """ | |
if len(a) == 0 or len(b) == 0: | |
return 0 | |
res = max( | |
LCS(a[:-1], b), | |
LCS(a, b[:-1]) | |
) | |
if a[-1] == b[-1]: | |
res = max(res, LCS(a[:-1], b[:-1]) + 1) | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment