三字母词的广度优先搜索,优化
我在 Python 中使用广度优先搜索算法来查找从三个字母的单词到另一个单词的最短“路径”。我已经让它工作了,但性能很糟糕,我怀疑我的单词“儿童生成”功能。
基本上,对于从队列中弹出的每个单词,我都会生成可以通过交换一个字母形成的所有其他三字母单词。该函数的工作原理如下:
#Pseudo code
For each position (1-3)
For each letter (a-z)
create a new word by exchanging the letter at the position
if this word is a valid word and is not used earlier
add it to the return list
return the list
这通常需要大约 0.03 秒。 有没有更快的方法来做到这一点?
I'm using a breadth-first search algorithm in Python to find the shortest "path" from a three-letter word to another. I've got it working but the performance is horrible and I suspect my word children generation function.
Basically for every word I pop from the queue I generate all other three-letter words that can be formed by exchanging one letter. The function works like this:
#Pseudo code
For each position (1-3)
For each letter (a-z)
create a new word by exchanging the letter at the position
if this word is a valid word and is not used earlier
add it to the return list
return the list
This usually takes about 0.03 seconds.
Is there a faster way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设您有一个有效单词列表,并且您实际上不是在寻找单个路径(为什么您要对此进行优化),而是在寻找许多路径。这可以通过 networkX 轻松完成:
感谢@Ducan 提供的示例单词。
如果您确实想自己实现这些算法,您可以在 wikipedia 找到大量描述。经典的单源最短路径算法是 Dijkstra's ,经典的所有对最短路径算法是 弗洛伊德-Warshall。
I assume that you have a list of valid words and you are actually not looking for a single path (why would you care to optimize for that) but for lots of paths. This can be done quite easily with networkX:
Thanks to @Ducan for the example words.
If you really want to implement these algorithms yourself you can find plenty descriptions at wikipedia. The classic single source shortest path algorithm is Dijkstra's and the classic all pairs shortest path algorithm is Floyd-Warshall.
如果你确实想重新发明轮子,也许这会有所帮助(注意,这已经设置了文字,因此至少需要 Python 2.7):
If you do want to reinvent the wheel, perhaps this would help (N.B. This has set literals so needs at least Python 2.7):
不要以可能次优的方式重新发明轮子:使用现有模块:
http://pypi.python。 org/pypi/altgraph/0.8
Instead of reinventing the wheel in a perhaps suboptimal way: use existing modules:
http://pypi.python.org/pypi/altgraph/0.8