Python基于动态规划算法计算单词距离
本文实例讲述了Python基于动态规划算法计算单词距离。分享给大家供大家参考。具体如下:
#!/usr/bin/envpython #coding=utf-8 defword_distance(m,n): """computetheleaststepsnumbertoconvertmtonbyinsert,delete,replace. 动态规划算法,计算单词距离 >>>printword_distance("abc","abec") 1 >>>printword_distance("ababec","abc") 3 """ len_1=lambdax:len(x)+1 c=[[i]foriinrange(0,len_1(m))] c[0]=[jforjinrange(0,len_1(n))] foriinrange(0,len(m)): #printi,'', forjinrange(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]+(0ifm[i]==n[j]else1)#改 ) ) #printc[i+1][j+1],m[i],n[j],'', #print'' returnc[-1][-1] importdoctest doctest.testmod() raw_input("Success!")
希望本文所述对大家的Python程序设计有所帮助。