问题:
给出两个单词word1和word2,写一个函数计算出将word1 转换为word2的最少操作次数。
你总共三种操作方法:
1、插入一个字符
2、删除一个字符
3、替换一个字符
格式:
输入行输入两个字符串 word1 和 word2,最后输出将 word1 转换为 word2的最少操作次数。
例如:
输入
word1 = "mart"
word2 = "karma"
输出
3
准备知识:
编辑距离及编辑距离算法
代码实现:
1.
def d(m, n): if m == 0 or n == 0: return abs(m - n) if word1[m - 1] == word2[n - 1]: return d(m - 1, n - 1) else: return min([d(m, n - 1) + 1, d(m - 1, n) + 1, d(m - 1, n - 1) + 1]) while True: word1 = input("word1=:") word2 = input("word2=:") print(d(len(word1), len(word2)))
2.
def minDis(word1,word2): m = len(word1)+1 n = len(word2)+1 dp = [[0 for i in range(n)] for j in range(m)] for i in range(n): dp[0][i] = i for i in range(m): dp[i][0] = i for i in range(1,m): for j in range(1,n): dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+(0 if word1[i-1]==word2[j-1] else 1)) return dp[m-1][n-1] if __name__ == '__main__': word1 = input('word1=') word2 = input('word2=') print(minDis(word1, word2))