Grids¶

🎨 print(..., end=' ')¶

In [ ]:
for i in range(4):
    print(i)
In [ ]:
for i in range(4):
    print(i, end=' ')
In [ ]:
for i in range(4):
    print(i, end='**')
In [ ]:
for i in range(4):
    print(i, end='\n')

NOTES

  • end= is a named argument.
  • We'll discuss how to make our own named arguments later.

🖌 Grids¶

In [ ]:
numbers = [
    [1, 2, 3],
    [4, 5, 6]
]

numbers

NOTES

  • Syntax: multiline representation of a list
  • Flat version (list of lists)
  • Draw this out
    • Visual: list of rows, row of items
    • Memory: heap, values, lists, references
In [ ]:
for row in numbers:
    for item in row:
        print(item, end=' ')
    print()

NOTES

  • discuss the code before you run it: what will it do?

👨🏿‍🎨 print_grid¶

Write a function that will print out any grid using spaces between each element in a row and newlines between each row.

In [ ]:
def print_grid(grid):
    for row in grid:
        # do something to print the row
        for item in row:
            print(item, end=' ')
        print()
    
In [ ]:
def print_grid(grid):
    for row in grid:
        for item in row:
            print(item, end=' ')
        print()
In [ ]:
print_grid(numbers)

👩🏼‍🎨 copy_grid¶

Write a function that creates a copy of a grid.

In [ ]:
def copy_list(stuff):
    new_stuff = []
    for thing in stuff:
        new_stuff.append(thing)
    return new_stuff


def copy_grid(grid):
    """Create a copy of the grid"""
    new_grid = []
    for row in grid:
        # Copy row
        new_row = []
        for item in row:
            new_row.append(item)
        new_grid.append(new_row)
    return new_grid
In [ ]:
def copy_grid(grid):
    # Create new grid
    new_grid = []
    for row in grid:
        # Create new row
        new_row = []
        for item in row:
            new_row.append(item)
        # Add new row to grid
        new_grid.append(new_row)
    # Return grid
    return new_grid
In [ ]:
numbers = [[1, 2, 3], [4, 5, 6]]
print(f'numbers: {numbers}')

more_numbers = copy_grid(numbers)
print(f"more   : {more_numbers}")
print()

print('more_numbers[0] = None')
more_numbers[0] = None

print(f'numbers: {numbers}')
print(f"more   : {more_numbers}")

👩🏾‍🎨 Empty Grid¶

Write a function that creates an empty grid (None in each cell) of specified dimensions.

In [ ]:
def empty_grid(num_rows, num_columns):
    """Create an empty grid (filled with None) with `num_rows` rows and `num_columns` columns."""
    the_grid = []
    for row_num in range(num_rows):
        # Create an empty row
        row = []
        for col_num in range(num_columns):
            row.append(None)
        the_grid.append(row)
    return the_grid


print_grid(empty_grid(3, 2))
In [ ]:
def empty_grid(num_rows, num_columns):
    new_grid = []
    for row in range(num_rows):
        new_row = []
        for column in range(num_columns):
            new_row.append(None)
        new_grid.append(new_row)
    return new_grid

print(empty_grid(3, 2))

Jagged Array¶

A grid where the rows are not all the same length is sometimes referred to as a jagged array.

👨🏾‍🎨 is_jagged¶

Write a function that returns True if the input grid is jagged.

In [ ]:
def is_jagged(grid):
    if len(grid) == 0:
        return False
    
    first_row = grid[0]
    for row in grid:
        if len(row) != len(first_row):
            return True
    return False
In [ ]:
def is_jagged(grid):
    size = None
    for row in grid:
        if size is None:
            size = len(row)
        elif len(row) != size:
            return True
    return False


def is_jagged(grid):
    if len(grid) == 0:
        return False
    
    size = len(grid[0])
    for row in grid:
        if len(row) != size:
            return True
    return False
In [ ]:
grid_a = [
    [1, 2, 3, 4],
    [5, 6, 7]
]
is_jagged(grid_a)
In [ ]:
grid_b = [
    [1, 2],
    [3, 4],
    [5, 6],
    [7, 8]
]
is_jagged(grid_b)

🧑🏼‍🎨 Parsing Grids¶

In [ ]:
%%file grid.txt
4 5 6 7
8 9 10 11
1 2 3 4

grid.txt¶

Write a function that reads a space-delimited file of integers into a grid.

In [ ]:
def load_grid(filename):
    with open(filename) as file:
        grid = []
        for line in file:
            split_line = line.split()
            row = []
            for i in split_line:
                row.append(int(i))
            grid.append(row)
    return grid

NOTES

  • Draw it out
    • draw the file, draw the resulting grid
      • what is the relationship between lines in the file and rows in the grid?
      • how do we break the file down to individual elements?
In [ ]:
def load_grid(filename):
    grid = []
    with open(filename) as file:
        for line in file:
            row = []
            for item in line.strip().split():
                row.append(int(item))
            grid.append(row)
    return grid
In [ ]:
grid = load_grid('grid.txt')
print(grid)

🧑🏽‍🎨 to_grid¶

Write a function that takes a list of items and turns it into a grid of specified dimensions.

Assume the number of items fits the dimensions perfectly.

In [ ]:
def to_grid(items, num_rows, num_columns):
    grid = []
    for row_num in range(num_rows):
        row = []
        for col_num in range(num_columns):
            # num_columns X row_num + col_num
            item_index = num_columns * row_num + col_num
            row.append(items[item_index])
        grid.append(row)
    return grid
In [ ]:
def to_grid(items, num_rows, num_columns):
    grid = []
    for row_num in range(num_rows):
        row = []
        for col_num in range(num_columns):
            row.append(items[row_num * num_columns + col_num])
        grid.append(row)
    return grid
In [ ]:
to_grid([1, 2, 3, 4, 5, 6], 3, 2)

Key Ideas¶

  • print(..., end=' ')
  • Grids
    • print a grid
    • copy a grid
    • create empty grid
  • Jagged arrays
  • Parsing grids
  • List to grid