Skip to content

Instantly share code, notes, and snippets.

@jleeothon
Last active August 29, 2015 14:07
Show Gist options
  • Save jleeothon/a295404147dfa2332620 to your computer and use it in GitHub Desktop.
Save jleeothon/a295404147dfa2332620 to your computer and use it in GitHub Desktop.
Python: recursive longest common subsequence (LCS) with dynamic programming
class DynamicLcs:
def __init__(self):
self.table = {}
@staticmethod
def run(s1, s2):
return DynamicLcs()._run(s1, s2)
def _run(self, s1, s2):
result = self.table.get(s1, s2)
if result is not None:
return result
if not s1 or not s2 == '':
return ''
if s1[0] == s2[0]:
self.table[{s1, s2}] = s1[0] + self._run(s1[1:], s2[1:])
else:
result1 = self._run(s1[1:], s2)
result2 = self._run(s1, s2[1:])
self.table[{s1, s2}] = max(result1, result2, key=len)
return self.table[{s1, s2}]
@jleeothon
Copy link
Author

# e.g.
a = "testmeiooooooiffffff"
b = "tioooo0oosieffffff"
print(DynamicLcs.run(a, b))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment