As usual, create a directory to hold today's files. All programs that you write today should be stored in this directory.
$ cd ~/cs120/labs $ mkdir lab30 $ cd lab30
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.
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 \times 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 super complicated.
Write a function check_magic_square(a_square)
, in a
file called square.py. This function takes some \(n \times
n\) 2-dimensional list of integers. It should return True
if the parameter is a magic square, and False otherwise.
>>> 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
You can use the built in sum
function to compute the sum of a particular row of the
square.
To assist your checks, you might want to write a function
called sum_column(a_square, column_number)
,
which will compute the sum of all of the values in the
specified column of the square. To sum a column, you need to
sum the column position from each row.
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.
One additional restriction, for an official magic square, is that every element in the magic square has to be unique. [[1, 1], [1, 1]] is not a magic square, for example. Add an additional check in your program to verify you have true magic squares.
In addition, there are some relatively straight forward algorithms
for generating a square which is guaranteed to be magic. Read the
Wikipedia
article for magic squares, and write a function
called generate_magic_square(size)
to generate a
magic square of the specified size.