Need help finishing a program
I need some help finishing this code. I don't expect you to give me the full answer, I just need some hint about the 2 functions. thanks
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 store开发者_如何学运维d 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!"
If all you want is a hint, take a look at Wikipedia's entry for the trie, which tells you everything you need to know about how tries work.
Okay, here's another hint: every node of the trie will contain a dictionary whose keys are characters and whose values are trie nodes. The insert
method will look at word[0]
, find or create the node for that character, and then, if len(word)
is greater than 1, do something with word[1:]
.
If Robert's hints aren't enough, here is a minimal implementation of a Trie with the two functions that you were having trouble with.
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
精彩评论