minte9
LearnRemember



Loop

Normal use of a for loop.
 
# Normal use of a for loop ...
#
# without list comprehension

str = "abc"
res = []

for s in str:
    res.append(s.capitalize())

assert res == ['A', 'B', 'C']

Comprehension

For loops can be write more concisely using list comprehension.
 
# List comprehension
#
# The loop variable appears in expression before we get to definition
# List comprehensions are more concise but are harder to debug

str = "abc"
res = [s.capitalize() for s in str]

assert res == ['A', 'B', 'C']

Application

List comprehension in action, convert matrix to tree.
  
""" Matrix to Tree
"""

matrix = [
    [3, 4],
    [8, [-2, 10], 5],
    7,
]

class Node:
    def __init__(self, value=None, children=[]):
        self.value = value
        self.children = children

def matrix_to_tree(m): # with For loop
    if isinstance(m, int):
        return Node(m, [])

    children = []
    for child in m:
        sub_node = matrix_to_tree(child)
        children.append(sub_node)
    return Node(None, children)

tree = matrix_to_tree(matrix)
assert tree.children[0].children[0].value == 3
assert tree.children[0].children[1].value == 4
assert tree.children[1].children[0].value == 8
assert tree.children[1].children[1].children[0].value == -2
assert tree.children[1].children[1].children[1].value == 10
assert tree.children[2].value == 7


def matrix_to_tree(m): # with List comprehension
    if isinstance(m, int):
        return Node(m, [])

    children = [matrix_to_tree(x) for x in m] # Look Here
    return Node(None, children)

tree = matrix_to_tree(matrix)
assert tree.children[0].children[0].value == 3
assert tree.children[0].children[1].value == 4
assert tree.children[1].children[0].value == 8
assert tree.children[1].children[1].children[0].value == -2
assert tree.children[1].children[1].children[1].value == 10
assert tree.children[2].value == 7
 



  Last update: 234 days ago