jimmyhuang0904
jimmyhuang0904

Reputation: 191

Python: Complicated iterables

I have seen this piece of code that iterates through certain members of a class if they exists. Notably, in a binary tree, iterating through the child until there are no more children.

Binary tree is defined as..

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

and they have iterated it like this:

# type root : TreeNode
def iterateTree(self, root):
    level_list = [root]

    while level_list:

        for item in level_list:
             print(item.val)

        # This iterable seems really complicated for me to understand how they came up with this
        level_list = [child for node in level_list for child in (node.left, node.right) if child]

I'm not sure how they came up with that line to iterate through the left and right node, I wouldn't have ever come up with that on the spot... How would I dissect this line?

Upvotes: 1

Views: 86

Answers (2)

Ogs
Ogs

Reputation: 166

if i'm not mistaken, this statement is a pythonic and short-hand way of creating a list.

 # This iterable seems really complicated for me to understand how they came up with this
   level_list = [child for node in level_list for child in (node.left, node.right) if child]

this is basically a shorthand way of doing the following set of lines:

for node in level_list:
    for child in (node.left, node.right):
        if child:
            level_list.append(child)

the trick to understanding this shorthand statement is by looking at the peripheral bounding symbols, in this case these are [ and ]. which identifies with the list sequence in python. since there are iterators (for loops) in the list, we are basically creating or adding elements (variable child) in the said list.

/ogs

Upvotes: 0

hopflink
hopflink

Reputation: 173

Read as follows:

for node in level_list:
    for child in (node.left, node.right):
        if child:
            child

Upvotes: 2

Related Questions