如何检查4x4矩阵是否是魔术广场?
我正在尝试检查二维阵列是否是魔术方形。对以下一个或多个方向的解释感到困惑?我以身作则学习最好,因此,如果有人可以直接向我展示代码,我将不胜感激。
写一个函数 接受二维列表作为参数,并确定列表是否为lo shu 魔法广场。测试程序中的功能。
您的程序应使用两个不同的输入来测试功能,一个符合魔术正方形的资格,而另一个则不符合魔术正方形的资格。在每个实例中,程序都应打印功能的结果
def main():
magicsquare = [[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]
notmagicsquare = [[10, 7, 4, 5], [2, 1, 0, 8], [8, 4, 6, 1], [4, 4, 5, 1]]
for r in range(rows):
for c in range(columns):
print(magicsquare)
for r in range(rows):
for c in range(columns):
print(notmagicsquare)
main()
I am trying to check if a two-dimensional array is a magic square. Getting confused about the interpretation of one or more of the directions below? I learn best by example so if anyone could show me directly with code I would appreciate it.
Write a function
that accepts a two-dimensional list as an argument and determines whether the list is a Lo Shu
Magic Square. Test the function in a program.Your program should test the function with two different inputs, one qualifying as a magic square and another that doesn't qualify as a magic square. In each instance, the program should print the result of the function
def main():
magicsquare = [[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]
notmagicsquare = [[10, 7, 4, 5], [2, 1, 0, 8], [8, 4, 6, 1], [4, 4, 5, 1]]
for r in range(rows):
for c in range(columns):
print(magicsquare)
for r in range(rows):
for c in range(columns):
print(notmagicsquare)
main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这对我有用,尝试和任何问题 - 请询问。
编辑:还检查
对角线
部分。感谢@albert积分。This works for me, try it and any questions - please ask.
Edit: also check the
diagonal
part. Thanks for @Albert points.在“魔术”正方形中,每行的总和必须相同。在Python 2维列表的上下文中,请记住,二维中的列表可能并非全部相同,那么检查您的正方形很重要。
例如:
输出:
In a "magic" square the sum of each row, column and diagonal must be the same. In the context of a Python 2-dimensional list and bearing in mind that the lists in the 2nd dimension may not all be of the same length, then it's important to check that you have a square.
For example:
Output:
假设a lo shu magic square 的每一列,行,对角线和反对道子的总和相同。
Assumed that a Lo Shu Magic Square has the same sum for every columns, rows, diagonal and anti-diagonal.