【问题标题】:Magic Square with Python使用 Python 的魔方
【发布时间】:2021-02-23 12:48:29
【问题描述】:

我有一个名为“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)

任何建议将不胜感激。

【问题讨论】:

  • 另一个想法是你可以反转幻方并找到它的“第一个对角线和”。

标签: python python-3.x list magic-square


【解决方案1】:

您可能会注意到另一条对角线的索引是(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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    相关资源
    最近更新 更多