I am new to Python generator. Here I want to do a post-order traversal of a tree. I found others' codes as follows. I don't quite understand it, instead, I wanted write it simply as the latter. So could anybody tell me why I was wrong?
def _loopallchildren(parent):
for child in parent.children:
if child.children:
for subchild in _loopallchildren(child):
yield subchild
yield child
wrong codes:
def _loopallchildren(parent):
for child in parent.children:
if child.children:
_loopallchildren(child)
yield child
For the same reason that merely calling _loopallchildren(root)
from the outside without doing anything with it doesn't do anything. You have to iterate over the generator to make use of it.
In Python ≥ 3.3 you can use yield from _loopallchildren(child)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.