I expet that this code should output:
8
8
but it does not.
class tree:
def __init__(self, size=2):
if size == 0:
return None
if size > 1:
half = size//2
self.left = tree(size-half)
self.right = tree(half)
else:
self.left = self.right = None
self.free = size
self.size = size
def resize(self,n):
while self.size < n:
t = tree(0)
t.left = self
t.right = tree(self.size)
t.free = t.left.size + t.right.size
t.size = self.size * 2
self = t
print("size in resize", self.size)
t = tree()
t.resize(5)
print("size of t", t.size)
output:
size in resize 8
size of t 2
I know I could do return self in resize and t = tree.resize(5) in main, but what if I want to return something else?
Karl’s answer is entirely right about everything, but there is certainly a way to make
resizeact as you’re expecting.Three steps:
Set the enlarged tree’s
leftto the copy of the original treeBasically, you were trying to do it backwards — replace
selfand reuseselfforself.left, instead of replacingself.leftand reusingself.