Created
December 16, 2012 04:47
-
-
Save moshekaplan/4303392 to your computer and use it in GitHub Desktop.
Sample code for recursively calculating the longest-common subsequence.
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
def lcs(str1, str2): | |
# If either string is empty, stop | |
if len(str1) == 0 or len(str2) == 0: | |
return "" | |
# First property | |
if str1[-1] == str2[-1]: | |
return lcs(str1[:-1], str2[:-1]) + str1[-1] | |
# Second proprerty | |
# Last of str1 not needed: | |
t1 = lcs(str1[:-1], str2) | |
# Last of str2 is not needed | |
t2 = lcs(str1, str2[:-1]) | |
if len(t1) > len(t2): | |
return t1 | |
else: | |
return t2 | |
if __name__ == "__main__": | |
print lcs('ALGORITHM','ALTRUISTIC') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment