我写了一个假设两个列表的答案,即要修剪的列表和有效单词的列表。在围绕我的答案进行的讨论中,我评论说也许一个 trie 解决方案会很好。
什么鬼,我继续写了。
您可以在此处阅读有关 trie 的信息:
http://en.wikipedia.org/wiki/Trie
对于我的 Python 解决方案,我基本上使用了字典。一个键是一个符号序列,每个符号进入一个字典,另一个 Trie 实例作为数据。第二个字典存储“终端”符号,它标志着 Trie 中“单词”的结尾。对于这个例子,“单词”实际上是单词,但原则上这些单词可以是任何可散列的 Python 对象序列。
Wikipedia 示例显示了一个 trie,其中键是字母,但可以不止一个字母;它们可以是多个字母的序列。为简单起见,我的代码一次只使用一个符号作为键。
如果将单词“cat”和单词“catch”都添加到 trie 中,那么将有 'c'、'a' 和 't' 的节点(以及 "抓住”)。在“a”的节点级别,“终端”字典中将包含“t”(从而完成“cat”的编码),同样在第二个“c”的更深节点级别,终端字典里面会有'h'(完成“catch”)。因此,在“cat”之后添加“catch”仅意味着在终端字典中增加一个节点和一个条目。 trie 结构提供了一种非常有效的方式来存储和索引一个非常大的单词列表。
def _pad(n):
return " " * n
class Trie(object):
def __init__(self):
self.t = {} # dict mapping symbols to sub-tries
self.w = {} # dict listing terminal symbols at this level
def add(self, word):
if 0 == len(word):
return
cur = self
for ch in word[:-1]: # add all symbols but terminal
if ch not in cur.t:
cur.t[ch] = Trie()
cur = cur.t[ch]
ch = word[-1]
cur.w[ch] = True # add terminal
def prefix_match(self, word):
if 0 == len(word):
return False
cur = self
for ch in word[:-1]: # check all symbols but last one
# If you check the last one, you are not checking a prefix,
# you are checking whether the whole word is in the trie.
if ch in cur.w:
return True
if ch not in cur.t:
return False
cur = cur.t[ch] # walk down the trie to next level
return False
def debug_str(self, nest, s=None):
"print trie in a convenient nested format"
lst = []
s_term = "".join(ch for ch in self.w)
if 0 == nest:
lst.append(object.__str__(self))
lst.append("--top--: " + s_term)
else:
tup = (_pad(nest), s, s_term)
lst.append("%s%s: %s" % tup)
for ch, d in self.t.items():
lst.append(d.debug_str(nest+1, ch))
return "\n".join(lst)
def __str__(self):
return self.debug_str(0)
t = Trie()
# Build valid list from /usr/dict/share/words, which has every letter of
# the alphabet as words! Only take 2-letter words and longer.
wfile = "/usr/share/dict/words"
for line in open(wfile):
word = line.strip()
if len(word) >= 2:
t.add(word)
# add valid 1-letter English words
t.add("a")
t.add("I")
lst = ["ark", "booze", "kite", "live", "rodeo"]
# "ark" starts with "a"
# "booze" starts with "boo"
# "kite" starts with "kit"
# "live" is good: "l", "li", "liv" are not words
# "rodeo" starts with "rode"
newlst = [w for w in lst if not t.prefix_match(w)]
print(newlst) # prints: ['live']