4/34
Part 1 of 8 · StepsLearn and do

A dict from name to function and one loop run any step list

Each step name maps to a function that takes a table and returns a new one:

def scale(table, factor):
    return [[value * factor for value in row] for row in table]


def clip(table, low, high):
    return [[min(max(value, low), high) for value in row] for row in table]


def each(table, func):
    return [[func(value) for value in row] for row in table]


def transpose(table):
    return [list(column) for column in zip(*table)]


def sort_by(table, column):
    if column >= len(table[0]):
        raise ValueError(f"no column {column} in a table {len(table[0])} wide")
    return sorted(table, key=lambda row: row[column])


def head(table, n):
    return table[:n]


TRANSFORMS = {"scale": scale, "clip": clip, "map": each, "transpose": transpose, "sort": sort_by, "head": head}

TRANSFORMS is a dict from name to function. It's the hash maps lesson's O(1) lookup, used as a dispatch table: look up the name, then call what you find. One loop runs any step list:

def run(table, steps):
    for name, *args in steps:
        table = TRANSFORMS[name](table, *args)
    return table

name, *args splits each step into its name and a list of its arguments. Then *args in the call spreads that list back out.

Predict

For the step ("transpose",), what is args?

Pick an answer above to see the rest