编辑距离
核心dp公式
# coding=utf-8
import numpy as np
def edit_distance(string1,string2):
len1=len(string1)
len2=len(string2)
matrix=np.zeros(shape=[len1+1,len2+1])
for i in range(len2):
matrix[0][i]=i
for j in range(len1):
matrix[j][0]=j
for i in range(1,len1+1):
for j in range(1,len2+1):
if string1[i-1]==string2[j-1]:
num_add=0
else:
num_add=1
matrix[i][j]=min(matrix[i-1][j-1]+num_add,matrix[i-1][j]+1,matrix[i][j-1]+1)
distance=matrix[len1-1][len2-1]
return distance
if __name__=='__main__':
string2='去哪里吃饭'
string1='去这里吃饭吧'
distance=edit_distance(string1=string1,string2=string2)
print('******************')
print(distance)