【问题标题】:Creating a magic square创建一个魔方
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 你必须将magic_square设置为你的“魔方”列表列表
    • 我不太明白你的意思
    • 抱歉,您的代码中似乎只是变量s。我会在几秒钟内改变我的答案
    【解决方案2】:

    不久前,我为一个编程拼图网站解决了一个类似的问题。我的问题范围更大——验证 NxN 数独谜题是否已正确解决。

    NxN 正方形中有两条对角线。

    import itertools
    
    square = [ [1, 2, 3],
               [4, 5, 6],
               [7, 8, 9] ]  # not a valid square!
    
    n = len(square)  # nxn square
    
    rows = iter(square)
    columns = zip(*square)  # this is a beautiful idiom! Learn it!
    diagonals = zip(*[(square[i][i], square[-i-1][i]) for i in range(n)])
    

    然后你可以做一个简单的sum检查

    sum(rows) == sum(columns) == sum(diagonals)
    

    代码中唯一奇怪的部分是列表推导的 zip 星号。基本上是这样的:

    diagonal1 = []
    diagonal2 = []
    for i in range(n):
        diagonal1.append(square[i][i])
        diagonal2.append(square[-i-1][i])
    diagonals = [diagonal1, diagonal2]
    

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多