CPSC150A
Scientific Computing

Activity 14

Nested Lists

Sum Column

Write a function called sum_column(a_matrix, col_index), which takes a 2-dimensional list and a positive integer as parameters. Your function should return the sum of all of the values along the specified column of the list.

Example

Test Code Output
print(sum_column([[1, 2, 3, 4, 5],[6, 7, 8, 9, 10]], 0)) 7
print(sum_column([[1, 2, 3, 4, 5],[6, 7, 8, 9, 10]], 2)) 11
print(sum_column([[1, 2, 3, 4, 5],[6, 7, 8, 9, 10]], -1)) 15
print(sum_column([[1, 2, 3, 4, 5],[6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], 0)) 18

Magic Squares

One interesting application of multidimensional lists are magic squares. Magic squares are a mathematical structure that has been studied for centuries. A magic square is an n by n 2-dimensional list such that the sum of each row, the sum of each column, and the sum of each diagonal are exactly the same. Constructing an magic square is a little bit complicated, but determining if a specified square is magic is not complicated.

Details

Write a function check_magic_square(a_square) that takes an n by n 2-dimensional list of integers. It should return True if the parameter is a magic square, and False otherwise.

Example

>>> square = [[8, 1, 6], [3, 5, 7], [4, 9, 2]]
>>> print(check_magic_square(square))
True
>>> square = [[8, 1, 10], [3, 5, 7], [4, 9, 2]]
>>> print(check_magic_square(square))
False
>>> square = [[17, 24, 1, 8, 15], [23, 5, 7, 14, 16], [4, 6, 13, 20, 22], [10, 12, 19, 21, 3], [11, 18, 25, 2, 9]]
>>> print(check_magic_square(square))
True

Hint

  • You can use the built-in sum function to compute the sum of a particular row of the square.

  • To compute the sum of a particular column, use the function you created in the practice problem.

  • You might also want to write functions called sum_major_diagonal(a_square), and sum_minor_diagonal(a_square). The major diagonal of a square 2-dimensional list are all of the values where the row identifier equals the column identifier. The minor diagonal is the opposite diagonal.

  • The check_magic_square function will need to compute the sum of one of the rows in the potentially magic square. Then, sum every row and check if it’s equal to the magic sum. Sum every column, check if it’s equal to the magic sum. Sum the two diagonals, and check if it’s equal to the magic sum. If any of them are not equal to the magic sum, then you don’t have a magic square.

Submission

Please show your source code and run your programs. Only programs that have perfect functionality will be accepted as complete.