Grids in Action¶

🎨 Keyword Arguments¶

In [ ]:
def print_with_bullets(lines, bullet='*'):
    for line in lines:
        print(f'{bullet} {line}')

NOTES

  • an argument becomes a keyword or named argument when you give it a default value in the function signature.
  • the value provided is the default value used when the caller does not provide a value
In [ ]:
lines = [
    'Hello.',
    'Cosmo is the best mascot.',
    'Python is pretty cool.'
]
In [ ]:
print_with_bullets(lines)
In [ ]:
print_with_bullets(lines, bullet='?')
In [ ]:
def print_more_stuff(stuff='stuff', lines):
    print(stuff)
    print(lines)

NOTES

  • arguments with defaults must be listed after regular arguments

👨🏼‍🎨 Pups in a Grid¶

🐶 🐶 🐶
🐶 🐶 🐶

We have a grid of puppies. We'll use 'p' to indicate a puppy at a given position.

A puppy is happy if it is next to another puppy. "Next to" means there is another puppy up, down, left, right, or diagonal of the given puppy.

Write a function to return the coordinates (row, column) of all the happy puppies in a grid.

happy_puppies.py¶

NOTES

  • DRAW IT OUT!
    • Discuss the logic: which puppies are happy?
    • Map out the strategy: iterate through all positions, check if happy, etc.
  • How do we search the neighborhood of a position?
    • Given row and column, what is the coordinate of the position above? to the right? diagonal down-left?
    • What if row and column are on the edge of the grid?
      • How do we ensure we don't try to check a position that doesn't exist?
      • What happens if you end up searching for [-1]?
  • Introduce logic of the guard expression using short-circut conditionals
    • if row - 1 >= 0 and grid[row - 1][column]...
  • Write out all 8 checks
    • where do you put the check for whether the current position is 'p'?
      • is_happy or find_happy?
In [ ]:
def is_happy(grid, row, column):
    if grid[row][column] != 'p':
        return False
    
    if row - 1 >= 0 and grid[row - 1][column] == 'p':
        return True
    if row + 1 < len(grid) and grid[row + 1][column] == 'p':
        return True
    if column - 1 >= 0 and grid[row][column - 1] == 'p':
        return True
    if column + 1 < len(grid[row]) and grid[row][column + 1] == 'p':
        return True
    
    if row - 1 >= 0 and column - 1 >= 0 and grid[row - 1][column - 1] == 'p':
        return True
    if row + 1 < len(grid) and column - 1 >= 0 and grid[row + 1][column - 1] == 'p':
        return True
    if row - 1 >= 0 and column + 1 < len(grid[row]) and grid[row - 1][column + 1] == 'p':
        return True
    if row + 1 < len(grid) and column + 1 < len(grid[row]) and grid[row + 1][column + 1] == 'p':
        return True
    
    return False


def find_happy(grid):
    happy = []
    for row in range(len(grid)):
        for column in range(len(grid[row])):
            if is_happy(grid, row, column):
                happy.append((row, column))
    return happy


grid = [
    [None, 'p', 'p'],
    ['p', None, None],
    [None, None, 'p']
]
find_happy(grid)

👩🏾‍🎨 print_grid¶

...but better

In [ ]:
def print_grid(grid):
    for row in grid:
        for item in row:
            print(item, end=' ')
        print()
In [ ]:
fruits = [
    ['apple', 'pear', 'guava'],
    ['orange', 'banana', 'peach'],
    ['melon', 'mango', 'kiwi']
]
print_grid(fruits)

Write a function that prints a grid.

Each individual column should have a consistent width:

apple  pear   guava
orange banana peach
melon  mango  kiwi

pretty_print_grid.py¶

NOTES

  • Draw this out
  • How do we know how wide to make a column?
    • pre-compute the column width
  • How do we know how much padding to add after a value?
    • full width minus value width
  • Handle non-str values also
    • What happens when you str a string?
In [ ]:
def pretty_print_grid(grid):
    widths = []
    for col in range(len(grid[0])):
        col_width = None
        for row in range(len(grid)):
            item_width = len(str(grid[row][col]))
            if col_width is None or item_width > col_width:
                col_width = item_width
        widths.append(col_width)
    
    for row in grid:
        for item, width in zip(row, widths):
            print(item, end=' ' * (width - len(str(item)) + 1))
        print()
In [ ]:
fruits = [
    ['apple', 'pear', 'guava'],
    ['orange', 'banana', 'peach'],
    ['melon', 'mango', 'kiwi']
]
pretty_print_grid(fruits)

print()

hodge_podge = [
    [1, 2, 3, 4, 5],
    [50, 123, 4.32, None, 43.21],
    ['so','much','amaze',':)', True]
]
pretty_print_grid(hodge_podge)

Review Lab 19¶

  • grid_game
  • others?

NOTES

  • How would you modify grid game so the user could specify the character to use instead of 'X'?