【发布时间】:2015-11-06 10:34:57
【问题描述】:
所以我正在创建一个魔方,这是我的代码
def is_magic_square(s): ''' 返回一个二维整数数组 s 是否魔法,即: 1) s 的维度是 nxn 2) [1,2,...,n*n] 中的每个整数在 s 中只出现一次。 3)s中所有行的总和与所有行的总和相同 s中的列,与对角线之和相同 s中的元素。
:param s: A two dimensional integer array represented as a nested list.
:return: True if square is magic, False otherwise
QUESTION 1: Write DocTest for
TEST Matricies that are magic a few different sizes, special cases seem to be, 1x1 matrix, 2x2 matrix.
>>> is_magic_square([[1]])
True
>>> is_magic_square([[8, 3, 4], [1, 5, 9], [6, 7, 2]])
True
YOUR TEST CASES GO HERE
NOTE:!!! LEAVE A BLANK LINE AFTER THE LAST TEST RESULT, BEFORE A COMMENT !!!
TEST Matricies that are not magic.
TEST NOT 1) The dimensions of s is nxn
>>> is_magic_square([[1,2],[3,4],[5,6]])
False
>>> is_magic_square([[1,2],[3,4,5],[6,7]])
False
YOUR TEST CASES GO HERE
>>>is_magic_square([[8, 3, 4], [1, 5, 9], [6, 7, 2]])
True
TEST NOT 2) Every integer in [1,2,...,n*n] appears in s, exactly once.
YOUR TEST CASES GO HERE
>>> is_magic_square([8, 3, 4],[9,3,3],[6,7,2])
False
TEST NOT 3) The sum of all rows in s is the same as the sum of all
columns in s, is the same as the sum of the diagonal
elements in s.
YOUR TEST CASES GO HERE
>>> is_magic_square([8,3,4], [1, 5, 9], [6,7,1])
False
nrows = len(s)
ncols = 0
if nrows != 0:
ncols = len(s[0])
if nrows != ncols:
return False
l = []
for row in s:
for elem in row:
if elem in l:
return False
l.append(elem)
m = sum(s[0])
for row in s:
sums = 0
for elem in row:
sums+=elem
if sums != m:
return False
return True
到目前为止,如果 nxn 正方形的长度是相同的长度、相同的总和等,我基本上测试了所有内容。我现在的问题是我试图计算对角线总和是否与行和列相同。我该怎么做?
【问题讨论】:
标签: python python-3.x