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')