我需要一些帮助才能完成此代码。我不指望你给我完整的答案,我只需要一些关于2个功能的提示。感谢
class Trie(object):
"""A Trie of TrieNodes. Trie has the following attributes:
-- _root: a TrieNode; the root of this Trie.
"""
def __init__(self):
"""Create an empty Trie."""
self._root = TrieNode()
def insert(self, word, data):
"""Insert the string 'word' with data 'data' into this Trie.
-- word: the string with which the newly inserted 'data' will
be associated.
-- data: the data which will be stored in the TrieNode
associated with the string 'word'.
If there is a TrieNode associated with the word 'word' in this
Trie, then _data of this TrieNode is updated to 'data'. Otherwise,
enough new TrieNodes are created and inserted into this Trie, to
create a TrieNode associated with 'word'.
"""
raise Exception, "Implement me!"
def find_node(self, word):
"""Return the TrieNode that corresponds to the string 'word'
in this Trie. Return None if there is no such TrieNode in this
Trie.
-- word: a string; the TrieNode that corresponds to 'word'
(if it exists) is returned.
"""
raise Exception, "Implement me!"
答案 0 :(得分:2)
如果您想要的只是一个提示,请查看Wikipedia's entry for the trie,它会告诉您有关尝试如何工作的所有信息。
好的,这是另一个提示:trie的每个节点都包含一个字典,其键是字符,其值是trie节点。 insert
方法将查看word[0]
,查找或创建该字符的节点,然后,如果len(word)
大于1,则使用word[1:]
执行某些操作。
答案 1 :(得分:0)
如果罗伯特的提示还不够,这里有一个Trie的最小实现,其中包含您遇到问题的两个函数。
class Trie(object):
def __init__(self, char='', data=None):
self.children = []
self.char = char
self.data = data
def get_child(self, char):
for child in self.children:
if child.char == char:
return child
def insert(self, key, data, node=None):
if node is None:
node = self
if len(key) == 0:
#key found
node.data = data
return node.data
else:
child = node.get_child(key[0])
if child is None:
child = Trie(key[0])
node.children.append(child)
return self.insert(key[1:], data, child)
return self.insert(key[1:], data, child)
def find(self, key, node=None):
if node is None:
node = self
if len(key) == 0:
#key found
return node.data
else:
child = node.get_child(key[0])
if child is None:
return None
return self.find(key[1:], child)
>>> tree = Trie()
>>> tree.insert('t', 't data')
>>> tree.insert('tr', 'tr data')
>>> print tree.find('t'), tree.find('tr')
t data tr data