编辑距离
Posted 幻觉czw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了编辑距离相关的知识,希望对你有一定的参考价值。
def init(alist, num1, num2):
dplist = alist
for i in range(num1 + 1):
dplist.append([])
for i in range(num1 + 1):
for j in range(num2 + 1):
dplist[i].append(0)
for i in range(1, num1 + 1):
dplist[i][0] = i
for j in range(1, num2 + 1):
dplist[0][j] = j
def dp(alist, list1, list2):
num1 = len(list1)
num2 = len(list2)
for i in range(1, num1 + 1):
for j in range(1, num2 + 1):
if list1[i - 1] != list2[j - 1]:
alist[i][j] = min(alist[i][j - 1],
alist[i - 1][j - 1],
alist[i - 1][j]) + 1
else:
alist[i][j] = min(alist[i][j - 1],
alist[i - 1][j - 1],
alist[i - 1][j])
for i in range(0, num1 + 1):
for j in range(0, num2 + 1):
if j == num2:
print alist[i][j]
else: print alist[i][j], ' ',
return alist[num1][num2]
def levenshtein(str1, str2):
alist = []
list1 = [i for i in str1]
list2 = [i for i in str2]
num1 = len(list1)
num2 = len(list2)
if num1 == 0:
return num2
if num2 == 0:
return num1
init(alist,num1, num2)
return dp(alist, list1, list2)
if __name__ == '__main__':
print levenshtein('sitting', 'kitten')
以上是关于编辑距离的主要内容,如果未能解决你的问题,请参考以下文章