Created
December 17, 2014 12:06
-
-
Save avenet/3a2b9fc0967215d2aca9 to your computer and use it in GitHub Desktop.
Longest common subsequence
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
def lcs(str1, str2): | |
return _lcs(str1, str2, 0, 0, "") | |
def _lcs(str1, str2, i, j, result): | |
if i==len(str1) or j==len(str2): | |
return result | |
str1_char = str1[i] | |
str2_char = str2[j] | |
if str1_char == str2_char: | |
return longest(str1, str2, i+1, j+1, result+str1_char) | |
first_alternative = longest(str1, str2, i+1, j, result) | |
second_alternative = longest(str1, str2, i, j+1, result) | |
return len(first_alternative) > len(second_alternative) and first_alternative or second_alternative | |
print lcs("andy", "andy venet") | |
print lcs("argentina", "aarg") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment