Cot->Cog->Dog 我不希望问题的解决方案只是指导我如何在此算法中使用 BFS? -6ren">
gpt4 book ai didi

algorithm - 如何计算两个单词之间的 "shortest distance"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:05:11 32 4
gpt4 key购买 nike

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

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

最佳答案

根据这个拼字游戏列表,猫和狗之间的最短路径是:['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']

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

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

关于algorithm - 如何计算两个单词之间的 "shortest distance"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11811918/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com