Skip to content

Instantly share code, notes, and snippets.

@aqzlpm11
Created June 28, 2017 09:33
Show Gist options
  • Save aqzlpm11/272e4ebcd060996fdf508ee2f434cea5 to your computer and use it in GitHub Desktop.
Save aqzlpm11/272e4ebcd060996fdf508ee2f434cea5 to your computer and use it in GitHub Desktop.
python: Longest common subsequence (LCS) algorithm
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