Python基于动态规划算法计算单词距离
本文实例讲述了Python基于动态规划算法计算单词距离。分享给大家供大家参考。具体如下:
#!/usr/bin/env python #coding=utf-8 def 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 doctest doctest.testmod() raw_input("Success!")
希望本文所述对大家的Python程序设计有所帮助。
相关推荐
yedaoxiaodi 2020-07-26
us0 2020-06-25
Eduenth 2020-06-22
Oudasheng 2020-06-13
sunjunior 2020-05-19
chenfei0 2020-04-30
老和山下的小学童 2020-04-20
SystemArchitect 2020-04-14
jiayuqicz 2020-02-02
zangdaiyang 2020-01-25
yuanran0 2020-01-20
yedaoxiaodi 2020-01-12
rein0 2020-01-01
Oudasheng 2019-12-27
Oudasheng 2019-12-22
wuxiaosi0 2019-12-17
trillionpower 2019-11-23
ustbfym 2019-11-03