我正在尝试编写一个 python 编辑距离,我写的代码只是比较两个单词,但是如果我想比较一个单词和一个单词列表呢?
这是我的代码:
def fdistance(S1,S2):
a = len(S1)
b = len(S2)
fdn = {} # Global dict
for x in range(a+1):
fdn[x,0] = x
for y in range(b+1):
fdn[0,y] = y
for x in range(1,a+1):
for y in range(1,b+1):
if S1[x-1] == S2[y-1]:
c = 0
else:
c = 1
fdn[x,y] = min(fdn[x,y-1]+1, fdn[x-1,y]+1, fdn[x-1,y-1]+c)
return fdn[x,y]
但它只能打印字符串与字符串之间的距离。我的问题是如果 S2 是一个列表,那么如何比较字符串和列表?
请您参考如下方法:
你有一个比较两个词的函数。
将单词与单词列表进行比较:
>>> words = ['halo', 'hallo', 'help']
>>> [fdistance('hello', word) for word in words]
[2, 1, 2]
