我有以下数据结构(Trie)的实现,它按预期工作。我有一个主类Node
和一个包装类Trie
。我想将函数_insert()
从Node
类移到Trie
类,以使Node
尽可能简单。但是我面临着很多问题,比如class Trie has no object nodes and no object word.
有没有一种方法可以在不将调用对象从main传入的情况下完成呢?
期望值:
trie.insert("Hi")
类Trie中insert()
的所有实现
class Node:
def __init__(self):
self.word = None
self.nodes = {}
def _insert(self, word, string_pos=0):
current_lettter = word[string_pos]
if current_lettter not in self.nodes:
self.nodes[current_lettter] = Node()
if(string_pos + 1 == len(word)):
self.nodes[current_lettter].word = word
else:
self.nodes[current_lettter]._insert(word, string_pos + 1)
return True
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
self.root._insert(word)
trie = Trie()
trie.insert("Hi")
类Trie(如实现的)没有对象节点和对象字
类Trie只有root.nodes和root.word对象
相关问题 更多 >
编程相关推荐