CS 115 Lab 9, Part A: Create a magic square

[Back to lab instructions]


Overview

A magic square is an N by N matrix whose elements contain the values 1 through N2, and where the sums of the values in each row, column, and diagonal are equal. Here is an example of a 5x5 magic square.

Magic square graphic

There is a simple algorithm for creating magic squares with odd values of N, such as the one above. You will see that algorithm shortly and will use it to write a program to create a magic square and verify that what it creates is indeed a magic square.


Instructions

  1. Create a new Python file called lab09a.py:

    """
    Program: CS 115 Lab 9a
    Author: Your name
    Description: This program will create a magic square
       whose size is specified by the user.
    """
    
    
    def create_list(rows, cols):
        """
        Creates a two-dimensional array.
    
        Parameters: the numbers of rows and columns
    
        Returns: a 2D array with all values set to zero
        """
    
        two_d = []  # create an empty list
        for i in range(rows):
            two_d.append([])  # append an empty list to two_d
            for j in range(cols):
                two_d[i].append(0)   # two_d[i] is the empty list that we just created.
                                     # here, we are adding elements to it.
        return two_d
    
    
    def rjust_by_n(number, n):
        """
        Return a string of length "n" with number right-justified in it.
    
        Parameters:
        number: an value with n or fewer digits
        n: a positive integer value
    
        Returns: a string of length n with a number right-justified in it.
        """
        return str(number).rjust(n)
    
    
    def print_list(numbers):
        """
        Print a 1D list of numbers, where each number is right-justified
        """
        for i in range(len(numbers)):
            print( rjust_by_n(numbers[i], 4), end='')
        print()
    
    
    def print_2d_list(two_d_list):
        """
        Print a 2-dimensional list
        """
        for i in range(len(two_d_list)):
            print_list(two_d_list[i])
    
    
    def main():
        # Your code goes here
    
    
    main()
  2. Read through the provided functions -- you will need to call some of them later.
  3. In main, ask the user to enter an integer to be used to create a magic square, and save that integer into a variable square_size.

    Sample input/output:

    Enter an odd integer to build a magic square: 5
  4. Make sure that the user's input (square_size) is odd. If it is not, print an error message and exit or return from main:
    Enter an odd integer to build a magic square: 6
    6 is not an odd integer. Terminating...
      
  5. If the input integer is odd, create a matrix (a two dimensional list) of that size and print it by right-justifying each value in exactly 4 spaces. Use the provided functions to help with this task. Creating the list should take 1 line of code, printing the blank line should take another, and printing the matrix should take 1 more.

    Enter an odd integer to build a magic square: 5
    
       0   0   0   0   0
       0   0   0   0   0
       0   0   0   0   0
       0   0   0   0   0
       0   0   0   0   0
    
  6. Copy and paste the following function in your program.
    def build_magic_square(square):
        """
        Create a magic square in "square"
        
        Parameter:
        square: a two dimensional array whose number of rows and columns are equal
                and len(square) is an odd number.
    
        Modifies "square" but doesn't return anything.
        """
        magic_value = 1
        square_size = len(square)
        row = 0
        col = square_size // 2
        square_size_squared = square_size * square_size
        while magic_value <= square_size_squared:
            square[row][col] = magic_value
            row -= 1
            col += 1
            if row < 0 and col > square_size - 1:
                row += 2
                col -= 1
            elif row < 0:
                row = square_size - 1
            elif col > square_size - 1:
                col = 0
            elif square[row][col] != 0:
                row += 2
                col -= 1
    
            magic_value += 1
    
  7. In main, insert a call to this function to build a magic square. This function call should go in between the lines of code that create and print the 2D list.

    Sample input/output:

    Enter an odd integer to build a magic square: 5
    
      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
    

    Another example:

    Enter an odd integer to build a magic square: 7
    
      30  39  48   1  10  19  28
      38  47   7   9  18  27  29
      46   6   8  17  26  35  37
       5  14  16  25  34  36  45
      13  15  24  33  42  44   4
      21  23  32  41  43   3  12
      22  31  40  49   2  11  20
    
  8. Continue to Part B.