< Back

Post Lab 19

2-d List Traversals

One topic that seems to give almost everyone in class a tough time is 2d lists. I noticed this again during the Minesweeper assignment as well. So again, we will get some practice with multi-dimensional lists today.


In a file called 2d_lists.py, write a function called sum_adjacent(a_2d_list, row, col). This function takes a 2-d list of integers elements as a parameter, as well as two integers row and col \((0 \leq row < len(a\_2d\_list) \mbox{ and }0 \leq col < len(a\_2d\_list[0]))\). This function should return a single integer, which is the sum of the 9 cell locations that are adjacent to the specified row and col, including the element at the index.

Two things to note:

  1. There is no guarantee that all 8 neighbors of the row and column exist, and
  2. You could write out all of the cases in multiple conditionals for the various edges and corners. But there is a much better way to deal with this.
You can combat both of these issues by writing an in_bounds function, and using a for loop to iterate through the potential neighboring locations.

Sample Test Cases

Function Parameters Expected Output
[[0, 1, 2], [3, 4, 5], [6, 7, 8]], 1, 1 36
[[0, 1, 2], [3, 4, 5], [6, 7, 8]], 0, 0 8
[[0]], 0, 0 0

Submission

Goto http://inquire.roanoke.edu/ You should see a section for post labs. Submit your .py file to the appropriate post lab location.

Post labs are to be done individually. Sharing files between students is not allowed. Doing so is an Academic Integrity violation, and will be treated as such.