Python 幻方

Magic Square with Python

我有一个名为“magic.txt”的文件,其中包含以下数字:

3
8 1 6
3 5 7
4 9 2

“3”代表正方形的NxN大小,其余数字是潜在的幻方。我编写的代码可以对所有行和列以及第一条对角线(即数字 8、5、2)求和。但是我不知道如何解决另一个对角线(即 6、5、4)。下面是我的第一个对角线代码。

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)

如有任何建议,我们将不胜感激。

您可能会注意到另一条对角线的索引是 (i, 2-i),或者在您的情况下是 (i, square_size-1-i)

所以你可以做类似于之前的事情

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)