所以我創建一個幻方,這裏是我的代碼創建幻方
高清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
我測試基本上一切都那麼遠,如果N×N的平方的長度是相同的長度,同樣的金額,等我的問題是,現在我試着去計算,如果對角和相同的行和柱。我會怎麼做?
magic_square沒有定義 – JerryMichaels
你必須設置magic_square作爲列出的清單是你的「幻方」 – George
我不太理解你的意思,由 – JerryMichaels