Naveen Piedy Naveen Piedy - 1 month ago 13
Python Question

Python generator doesn't iterate

I am trying to do a tree traversal but the problem is the yield returns a generator object but I am not able to iterate the generator object. I am very new to python, so any help will be appreciated.

def inorder_keys(self):
try:
if self.flag:
self.head = self.root
self.head_key = self.root_key
self.flag = False
if self.head.left is not None:
self.head_key = self.head.left
self.head = self.dict_of_keys[self.head_key]
BinarySearchTreeDict.inorder_keys(self)
else:
yield self.head_key
yield self.head.parent
#print(self.head_key)
#print(self.head.parent)
temp = self.head.parent
self.head = self.dict_of_keys[temp]
self.head = self.dict_of_keys[self.head.right]
BinarySearchTreeDict.inorder_keys(self)
except KeyError:
self.flag = True
pass



try:
x = object01.inorder_keys()
print(''.join(x))
except Exception as e:
print(str(e))


Output:

C:\Python34\python.exe "...\output.py"
Process finished with exit code 0

2ps 2ps
Answer

So, your data structure seems awfully weird to me, but here is the general pattern that you want to use:

def inorder_keys(self):
    if self.head.left is not None:
        yield from self.head.left.inorder_keys()
    yield self.head_key
    if self.head.right is not None:
        yield from self.head.right.inorder_keys()

And that’s it if I am understanding your data structure correctly.

Comments