class Node:
def __init__(self, key, parent = None):
self.key = key
self.parent = parent
self.left = None
self.right = None
if parent != None:
if key < parent.key:
parent.left = self
else:
parent.right = self
def search(self, key):
if self == None:
return (False, None)
if self.key == key:
return (True, self)
elif self.key > key:
return self.left.search(key)
elif self.key < key:
return self.right.search(key)
else:
return (False, self)
t1 = Node(25)
t2 = Node(12, t1)
t3 = Node(18, t2)
t4 = Node(40, t1)
print('-- Testing search -- ')
(b, found_node) = t1.search(18)
assert b and found_node.key == 18, 'test 8 failed'
(b, found_node) = t1.search(25)
assert b and found_node.key == 25, 'test 9 failed'
(b, found_node) = t1.search(26)
assert(not b), 'test 10 failed'
assert(found_node.key == 40), 'test 11 failed'
Traceback (most recent call last):
File "/Users/user/PycharmProjects/practice/main.py", line 50, in <module>
(b, found_node) = t1.search(26)
File "/Users/user/PycharmProjects/practice/main.py", line 27, in search
return self.right.search(key)
File "/Users/user/PycharmProjects/practice/main.py", line 25, in search
return self.left.search(key)
AttributeError: 'NoneType' object has no attribute 'search'
My search function is getting an error with the recursive calls to search(self.left, key) and search(self.right, key). It says search() takes 2 positional arguments, but is getting 3, and I am not understanding how this is happening?
Node.search(self.left, key)andNode.search(self.right, key). Since you're invoking thesearchmethod of theselfinstance, theselfinstance gets passed implicitly as the first argument.self.left.search(key). Remember that callingself.searchsuppliesselfas the automatic first parameter.selfwill never beNone, unless you unconventionally callNode.searchdirectly rather than via an instance ofNode. Whenself.leftisNone,self.left.search(...)is anAttributeError, not the same asNode.search(None, ...).