如何计算两个单词之间的"最短距离"?

Dud*_*ude 3 algorithm graph-theory data-structures

最近我接受了采访,我被要求编写一个算法来查找从特定单词到给定单词的最小1个字母变化数,即Cat-> Cot-> Cog-> Dog

我不希望问题的解决方案只是指导我如何在此算法中使用BFS?

jan*_*isz 5

乍一看我想到了Levenshtein 距离,但你需要使用 BFS。所以我认为你应该从构建树开始。给定的单词应该是根,然后下一个节点是首字母已更改的单词。下一个节点已更改第二个字母。当你构建图表时,你使用 BFS,当你发现新单词时,存储路径长度。在算法结束时选择最小距离。


rob*_*ing 5

根据这个拼字游戏列表,猫与狗之间的最短路径是:['CAT','COT','COG','DOG']

from urllib import urlopen

def get_words():
    try:
        html = open('three_letter_words.txt').read()
    except IOError:
        html = urlopen('http://www.yak.net/kablooey/scrabble/3letterwords.html').read()
        with open('three_letter_words.txt', 'w') as f:
            f.write(html)

    b = html.find('<PRE>') #ignore the html before the <pre>
    while True:
        a = html.find("<B>", b) + 3
        b = html.find("</B>", a)
        word = html[a: b]
        if word == "ZZZ":
            break
        assert(len(word) == 3)
        yield word

words = list(get_words())

def get_template(word):
    c1, c2, c3 = word[0], word[1], word[2]
    t1 = 1, c1, c2
    t2 = 2, c1, c3
    t3 = 3, c2, c3
    return t1, t2, t3

d = {}
for word in words:
    template = get_template(word)
    for ti in template:
        d[ti] = d.get(ti, []) + [word] #add the word to the set of words with that template

for ti in get_template('COG'):
    print d[ti]
#['COB', 'COD', 'COG', 'COL', 'CON', 'COO', 'COO', 'COP', 'COR', 'COS', 'COT', 'COW', 'COX', 'COY', 'COZ']
#['CIG', 'COG']
# ['BOG', 'COG', 'DOG', 'FOG', 'HOG', 'JOG', 'LOG', 'MOG', 'NOG', 'TOG', 'WOG']

import networkx
G = networkx.Graph()

for word_list in d.values():
    for word1 in word_list:
        for word2 in word_list:
            if word1 != word2:
                G.add_edge(word1, word2)

print G['COG']
#{'COP': {}, 'COS': {}, 'COR': {}, 'CIG': {}, 'COT': {}, 'COW': {}, 'COY': {}, 'COX': {}, 'COZ': {}, 'DOG': {}, 'CON': {}, 'COB': {}, 'COD': {}, 'COL': {}, 'COO': {}, 'LOG': {}, 'TOG': {}, 'JOG': {}, 'BOG': {}, 'HOG': {}, 'FOG': {}, 'WOG': {}, 'NOG': {}, 'MOG': {}}

print networkx.shortest_path(G, 'CAT', 'DOG')
['CAT', 'OCA', 'DOC', 'DOG']
Run Code Online (Sandbox Code Playgroud)

作为奖励,我们可以获得最远的奖励:

print max(networkx.all_pairs_shortest_path(G, 'CAT')['CAT'].values(), key=len)
#['CAT', 'CAP', 'YAP', 'YUP', 'YUK']
Run Code Online (Sandbox Code Playgroud)

  • 家庭作业标签意味着您应该提供指南,而不是完整的答案,如标签说明中所述:"这可以让潜在的答案者知道他们应该引导学生解决问题,并且不应该只是显示完整的答案.请避免这样做将来 (5认同)