Working on LeetCode #1032, I'm having a problem that appears related to having embedded classes. Here is the code:
from collections import deque
class StreamChecker:
def __init__(self, words):
self.RPT = StreamChecker.ReversePrefixTree( StreamChecker.ReversePrefixTreeNode )
def query(self, letter):
...
class ReversePrefixTreeNode:
def __init__( self ):
self.char_dict = {} # Key is char from word, value is successor node
self.words = [] # All words that complete at this node
def successor( self, char ):
return self.char_dict.get( char, None )
def getWords( self ):
return self.words
def __str__( self ): f"[ RPTNode: char_dict = { self.char_dict }, words = { self.words } ]"
class ReversePrefixTree:
def __init__( self, root ):
self.root = root
def insert( self, word ):
node = self.root
for char in reversed( word ):
if char in node.char_dict:
node = node.char_dict[ char ]
else:
next_node = ReversePrefixTreeNode()
node.char_dict[ char ] = next_node
node = next_node
node.words.append( word )
def tester():
obj = StreamChecker( [ "here", "are", "some", "words" ] )
print( "obj", obj, "obj.RPT", obj.RPT )
print( "obj.RPT.root", obj.RPT.root.getWords() ) <<<=========== Problem statement
tester()
I get the following error message:
obj <__main__.StreamChecker object at 0x00000213C5FB1710> obj.RPT <__main__.StreamChecker.ReversePrefixTree object at 0x00000213C5FB3E50>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[22], line 41
38 print( "obj", obj, "obj.RPT", obj.RPT )
39 print( "obj.RPT.root", obj.RPT.root.getWords() )
---> 41 tester()
Cell In[22], line 39, in tester()
37 obj = StreamChecker( [ "here", "are", "some", "words" ] )
38 print( "obj", obj, "obj.RPT", obj.RPT )
---> 39 print( "obj.RPT.root", obj.RPT.root.getWords() )
TypeError: StreamChecker.ReversePrefixTreeNode.getWords() missing 1 required positional argument: 'self'
I am flummoxed by the meaning of the last sentence. Aren't I giving a value "object path" to get what I want?
self.RPT = StreamChecker.ReversePrefixTree( StreamChecker.ReversePrefixTreeNode)I'm guessing the last part should beStreamChecker.ReversePrefixTreeNode()instead, so that you're creating an instance of that class, not referring to the class itself.StreamChecker.ReversePrefixTreeconstructor, it isn't caused by nesting your classes, but why do this to begin with? Is this name spacing really helpful?next_node = ReversePrefixTreeNode(),should benext_node = StreamChecker.ReversePrefixTreeNode()