Day23:求出两个字符串之间的编辑距离
eg:input :str1 = "intention" str2 = "execution"
output : 5
#详细解释参见链接 https://www.cnblogs.com/xiaodangdang/p/12165303.html
1 def string_distance(str1, str2): 2 """ 3 计算两个字符串之间的编辑距离 4 @author: 5 @date: 6 :param str1: 7 :param str2: 8 :return: 9 """ 10 m = len(str1) 11 n = len(str2) 12 distance = np.zeros((m + 1, n + 1)) 13 14 for i in range(0, m + 1): 15 distance[i, 0] = i 16 for i in range(0, n + 1): 17 distance[0, i] = i 18 19 for i in range(1, m + 1): 20 for j in range(1, n + 1): 21 if str1[i - 1] == str2[j - 1]: 22 cost = 0 23 else: 24 cost = 1 25 distance[i, j] = min(distance[i - 1, j] + 1, distance[i, j - 1] + 1, 26 distance[i - 1, j - 1] + cost) # 分别对应删除、插入和替换 27 28 return distance[m, n] 29 30 31 if __name__ == '__main__': 32 str1 = "intention" 33 str2 = "execution" 34 result = string_distance(str1, str2) 35 print(result)
输出结果 : 5