编辑距离字符串和列表

时间:2015-11-12 16:13:44

标签: python

我正在尝试编写一个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是一个列表,那么如何比较字符串和列表?

1 个答案:

答案 0 :(得分:2)

你有一个比较两个单词的功能。

将单词与单词列表进行比较:

>>> words = ['halo', 'hallo', 'help']
>>> [fdistance('hello', word) for word in words]
[2, 1, 2]
相关问题