创造一个魔方

时间:2015-11-06 02:06:46

标签: python python-3.x

所以我创建了一个魔术广场,这是我的代码

def is_magic_square(s):     '''     返回二维整数数组s是否为魔术,即:     1)s的尺寸是nxn     2)[1,2,...,n * n]中的每个整数都出现在s中,恰好是一次。     3)s中所有行的总和与all的总和相同        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方块的长度是相同的长度,相同的总和等,我基本上测试了到目前为止的一切。我的问题是现在我试图计算对角线和是否与行和列相同。我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以通过执行来计算对角线总和 sum([ s[i][i] for i in range(len(s))])sum([ s[len(s)-i-1][i] for i in range(len(s))])s变量是您正在测试的列表列表

答案 1 :(得分:2)

我不久前为编程拼图网站解决了类似的问题。我的问题范围有点大 - 确认NxN数独谜题得到了妥善解决。

你在NxN广场上有两个对角线。

select order.orderid,
       ad1.Addressline1,
       ad1.Addressline2,
       ad2.Addressline1,
       ad2.Addresslinne2 
from order
join address ad1 on ad1.id=order.billingaddressid
join address ad2 on ad2.id=order.shippingaddressid

然后你可以做一个简单的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

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

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