I wrote this code to test prefix tree, but for some reason I get the error "TrieNode" object is not callable. Could someone help me resolve this error?
Why is the TrieNode() class not callable?
# Prefix Tree or Trie Data Structure
class TrieNode(object):
def __init__(self):
self.children = {}
self.endOfWord = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self,word):
node = self.root()
for w in word:
if w not in node.children:
node.children[w] = TrieNode()
node = node.children[w]
node.endOfWord = True
def search(self,word):
node = self.root
for w in word:
if w not in node.children:
return False
node = node.children[w]
return node.endWord
def startsWith(self,prefix):
node = self.root
for w in prefix:
if w not in node.children:
return False
node = node.children[w]
return True
if __name__ == "__main__":
trie = Trie()
trie.insert("apple")
trie.insert("apples")
trie.insert("bat")
trie.insert("bate")
print trie.search("apple")
It should read
def insert(self,word):
node = self.root
Watch the root()
-> root
there. You are currently calling an instance attribute while in fact you only want to get a reference to it.