1. 程式人生 > >動態分析求('abc'-> 'xy')

動態分析求('abc'-> 'xy')

使用動態分析求解,abc->xy,需要幾步操作

增加、刪除、替換一個字母算一步

# -*- coding: UTF-8 -*-

start = 'abc'
end = 'yz'

s = len(start) + 1
e = len(end) + 1

# 生成二維陣列
arr = [[0 for i in range(e)] for j in range(s)]
for i in range(e):
    arr[0][i] = i

for i in range(1, s):
    arr[i][0] = i
    for j in range(1, e):
        if start[i-1] == end[j-1]:
            arr[i][j] = arr[i-1][j-1]
        else:
            arr[i][j] = min(arr[i-1][j-1], arr[i][j-1], arr[i-1][j]) + 1            

print(arr[s-1][e-1])