I'm trying to recursively iterate through all my nodes, however I get an infinite loop.
class Dictionary:
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.nextNode = None
def insert(self, key, value):
if self.nextNode is None or key < self xss=removed xss=removed xss=removed class="hljs-keyword">elif key > self.nextNode.key:
self.nextNode.insert(key, value)
else:
pass
def __iter__(self):
if self.nextNode is None:
return self
else:
return self.__next__().__iter__()
def __next__(self):
return self.nextNode
def __str__(self):
return f'{self.key} : {self.value}'
def __init__(self):
self.__head = None
def insert(self, key, value):
if self.__head is None or key < self xss=removed xss=removed xss=removed class="hljs-keyword">elif key > self.__head.key:
self.__head.insert(key, value)
else:
pass
def __iter__(self):
return self.__head
def __str__(self):
return str(self.__head)
d = Dictionary()
d.insert(2, 2)
d.insert(3, 3)
d.insert(4, 4)
d.insert(5, 5)
When I do:
p = iter(d)
print(p)
print(next(p))
print(next(next(p))
it works, but when I do
for i in p:
print(i)
I get an infinite loop that prints 3s. It doesn't even jump nodes.
Isn't a for loop just the same thing as doing iter() and then using next() a bunch of times until I hit a condition (None)? Shouldn't I be getting the same thing for these? What am I doing wrong?