Exercise: Nested lists
Try out iterating through nested lists and computing different things in the exercises below. These are a great practice for this unit's project, as it will involve a lot of nested lists.
Sum Grid
Implement sum_grid
, a function that returns the sum of all the numbers in grid
, a 2-dimensional list of numbers.
📺 Need help getting started? Here's a video walkthrough of a similar problem.
🧩 Or, for more guidance in written form, try a Parsons Puzzle version first.
def sum_grid(grid):
"""Returns the sum of all the numbers in the given grid, a 2-D list of numbers.
>>> grid1 = [
... [5, 1, 6], # 12
... [10, 4, 1], # 15
... [8, 3, 2] # 13
... ]
>>> sum_grid(grid1)
40
>>> grid2 = [
... [15, 1, 6], # 22
... [10, 4, 0], # 14
... [8, 3, 2] # 13
... ]
>>> sum_grid(grid2)
49
"""
# Initialize a sum to 0
# Iterate through the grid
# Iterate through current row
# Add current value to sum
# Return sum
Contains 15 row?
Implement contains_15row
, a function that returns true if any of the rows in grid
, a 2-dimension list of numbers, add up to a total of 15.
🧩 For more guidance, try a Parsons Puzzle version first.
def contains_15row(grid):
"""Takes an input of a 2-dimensional list of numbers
and returns true if any of the rows add up to 15.
>>> grid1 = [
... [5, 1, 6], # 12
... [10, 4, 1], # 15!!
... [8, 3, 2] # 13
... ]
>>> contains_15row(grid1)
True
>>> grid2 = [
... [15, 1, 6], # 22
... [10, 4, 0], # 14
... [8, 3, 2] # 13
... ]
>>> contains_15row(grid2)
False
"""
# Iterate through the grid
# Initialize a sum to 0
# Iterate through the row
# Add current value to sum
# If sum is 15, return true
# return false otherwise