Created
March 11, 2020 06:21
-
-
Save littlepea/0d9326a55f8479c5b70766eb37e4bcf3 to your computer and use it in GitHub Desktop.
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
class memorize(dict): | |
def __init__(self, func): | |
self.func = func | |
def __call__(self, *args): | |
return self[args] | |
def __missing__(self, key): | |
self[key] = self.func(*key) | |
return self[key] | |
@memorize | |
def deletion_distance(str1, str2): | |
if not str1: | |
return len(str2) | |
if not str2: | |
return len(str1) | |
if str1[0] == str2[0]: | |
return deletion_distance(str1[1:], str2[1:]) | |
return min( | |
1 + deletion_distance(str1[1:], str2), | |
1 + deletion_distance(str1, str2[1:]) | |
) | |
memo = {} | |
def deletion_distance_with_memo(str1, str2): | |
key = (str1, str2) | |
if key in memo: | |
return memo[key] | |
if not str1: | |
memo[key] = len(str2) | |
elif not str2: | |
memo[key] = len(str1) | |
elif str1[0] == str2[0]: | |
memo[key] = deletion_distance(str1[1:], str2[1:]) | |
else: | |
memo[key] = min( | |
1 + deletion_distance(str1[1:], str2), | |
1 + deletion_distance(str1, str2[1:]) | |
) | |
return memo[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment