Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離
來(lái)源:懂視網(wǎng)
責(zé)編:小采
時(shí)間:2020-11-27 14:42:09
Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離
Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離:本文實(shí)例講述了Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離。分享給大家供大家參考。具體如下: #!/usr/bin/env python #coding=utf-8 def word_distance(m,n): compute the least steps number to convert m to n by
導(dǎo)讀Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離:本文實(shí)例講述了Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離。分享給大家供大家參考。具體如下: #!/usr/bin/env python #coding=utf-8 def word_distance(m,n): compute the least steps number to convert m to n by
本文實(shí)例講述了Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離。分享給大家供大家參考。具體如下:
#!/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 .
動(dòng)態(tài)規(guī)劃算法,計(jì)算單詞距離
>>> 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!")
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離
Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離:本文實(shí)例講述了Python基于動(dòng)態(tài)規(guī)劃算法計(jì)算單詞距離。分享給大家供大家參考。具體如下: #!/usr/bin/env python #coding=utf-8 def word_distance(m,n): compute the least steps number to convert m to n by