【发布时间】: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