Search code examples
pythonpython-3.xlistmagic-square

Magic Square with Python


I have a file called "magic.txt" which contains the following numbers:

3
8 1 6
3 5 7
4 9 2

The "3" stands for the NxN size of the square, and the rest of the numbers is the potential magic square. I wrote code that can sum up all the rows and the columns and the first diagonal (namely, the numbers 8, 5, 2). However I have no clue how to solve for the other diagonal (namely, 6, 5, 4). Below is my code for the first diagonal.

def sum_diagonal():
    with open("magic.txt") as file:
        text = file.readlines() # Read magic.txt file

        square_size = int(text.pop(0)) # Pop off the square size from the list and converting it to an integer
        terminator = int(text.pop(square_size)) # Pop off the -1 terminator

        sumdia1 = 0
        for x in range(square_size): # This for loop is to loop through all the rows and add up the diagonal.
            text_list = text[x].split() # Splits the y-th index into its own list (multi-dimensional list)
            sumdia1 = sumdia1 + int(text_list[x]) # Sum up the diagonal 1
        print("Sum of diagonal 1:", sumdia1)

Any suggestions would be appreciated.


Solution

  • You may notice the index of the other diagonal is (i, 2-i), or (i, square_size-1-i) in your case.

    So you can do something similar to before

    def sum_diagonal():
        with open("magic.txt") as file:
            text = file.readlines() # Read magic.txt file
    
            square_size = int(text.pop(0)) # Pop off the square size from the list and converting it to an integer
            terminator = int(text.pop(square_size)) # Pop off the -1 terminator
    
            sumdia1 = 0
            for x in range(square_size): # This for loop is to loop through all the rows and add up the diagonal.
                text_list = text[x].split() # Splits the y-th index into its own list (multi-dimensional list)
                sumdia1 = sumdia1 + int(text_list[x]) # Sum up the diagonal 1
            print("Sum of diagonal 1:", sumdia1)
    
            sumdia2 = 0
            for x in range(square_size): # This for loop is to loop through all the rows and add up the diagonal.
                text_list = text[x].split() # Splits the y-th index into its own list (multi-dimensional list)
                sumdia2 = sumdia2 + int(text_list[square_size-1-x]) # Sum up the diagonal 1
            print("Sum of diagonal 2:", sumdia2)