【发布时间】:2012-01-15 21:03:30
【问题描述】:
在块日历的背面,我发现了以下谜语:
你能从这些字母中拼出多少个4个或更多字母的常用英语单词 “教科书”这个词(每个字母只能使用一次)。
我想出的第一个解决方案是:
from itertools import permutations
with open('/usr/share/dict/words') as f:
words = f.readlines()
words = map(lambda x: x.strip(), words)
given_word = 'textbook'
found_words = []
ps = (permutations(given_word, i) for i in range(4, len(given_word)+1))
for p in ps:
for word in map(''.join, p):
if word in words and word != given_word:
found_words.append(word)
print set(found_words)
这给出了结果set(['tote', 'oboe', 'text', 'boot', 'took', 'toot', 'book', 'toke', 'betook']),但在我的机器上花了超过 7 分钟。
我的下一个迭代是:
with open('/usr/share/dict/words') as f:
words = f.readlines()
words = map(lambda x: x.strip(), words)
given_word = 'textbook'
print [word for word in words if len(word) >= 4 and sorted(filter(lambda letter: letter in word, given_word)) == sorted(word) and word != given_word]
几乎立即返回答案,但作为答案给出:['book', 'oboe', 'text', 'toot']
解决这个问题的最快、正确和最 Pythonic 的解决方案是什么?
(编辑:添加了我之前的排列解决方案及其不同的输出)。
【问题讨论】:
-
在看到您的评论之前删除了我的答案,原因与您指出的相同。谢谢
-
您可以通过对 dict 进行一些预处理并为每个字母分配一个素数表示来非常有效地解决这个问题。如果以后有时间我会写一个解决方案。
-
@Voo 我会等待选择正确答案,直到您提交解决方案。我很期待。
-
这个问题似乎跑题了,因为它是关于编程难题的 (codegolf.stackexchange.com)
标签: python algorithm permutation puzzle