Python 动态规划算法,计算单词距离,python算法,#!/usr/bin/e
文章由Byrx.net分享于2019-03-23 08:03:55
Python 动态规划算法,计算单词距离,python算法,#!/usr/bin/e
#!/usr/bin/env python#coding=utf-8def word_distance(m,n): """compute the least steps number to convert m to n by insert , delete , replace . 动态规划算法,计算单词距离 >>> print word_distance("abc","abec") 1 >>> print word_distance("ababec","abc") 3 """ len_1=lambda x:len(x)+1 c=[[i] for i in range(0,len_1(m)) ] c[0]=[j for j in range(0,len_1(n))] for i in range(0,len(m)): # print i,' ', for j in range(0,len(n)): c[i+1].append( min( c[i][j+1]+1,#插入n[j] c[i+1][j]+1,#删除m[j] c[i][j] + (0 if m[i]==n[j] else 1 )#改 ) ) # print c[i+1][j+1],m[i],n[j],' ', # print '' return c[-1][-1]import doctestdoctest.testmod()raw_input("Success!")#该片段来自于http://byrx.net
评论关闭