gpt4 book ai didi

python - 创建一个幻方

转载 作者:太空宇宙 更新时间:2023-11-04 10:19:00 25 4
gpt4 key购买 nike

所以我正在创建一个幻方,这是我的代码

def is_magic_square(s): ''' 返回一个二维整型数组s是否是magic,即: 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 正方形的长度相同、总和等相同,我基本上测试了所有内容。我现在的问题是我正在尝试计算对角线总和是否与行和列相同。我该怎么做?

最佳答案

您可以通过以下方式计算对角线和sum([ s[i][i] for i in range(len(s))])sum([ s[len(s)-i-1][i] for i in range(len(s))]),其中 s 变量是您正在测试的列表列表

关于python - 创建一个幻方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33558286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com