Last active
August 29, 2015 14:07
-
-
Save jleeothon/a295404147dfa2332620 to your computer and use it in GitHub Desktop.
Python: recursive longest common subsequence (LCS) with dynamic programming
This file contains 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
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}] |
Author
jleeothon
commented
Oct 5, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment