简体   繁体   English

Python - 确定列表是否对称的算法

[英]Python - Algorithm to determine if a list is symmetric

So I'm stuck on this problem where I've been asked to write an function in Python that checks to see if an n-dimensional array (is that what they're called?) is "symmetric" or not, meaning that row 1 of the array == column 1, row 2 == column 2, row 3 == column 3, etc so on and so forth. 所以我一直坚持这个问题,我被要求在Python中编写一个函数来检查n维数组(它们被称为是什么?)是否是“对称的”,意思是行数组中的1 = =第1列,第2行==第2列,第3行==第3列,等等等等。 The goal is to have a function that returns the boolean True if its symmetric, and False if its not. 目标是有一个函数,如果它是对称的,则返回布尔值True,否则返回False。

I've managed to write a function that works, but it only work on lists whose sizes are perfect squares, (eg 2 x 2, 4 x 4), and a few of my test cases are of "irregular" sizes (eg 2 x 5, 3 x 2). 我已经设法编写了一个有效的功能,但它只适用于尺寸为完美正方形的列表(例如2 x 2,4 x 4),并且我的一些测试用例具有“不规则”尺寸(例如2 x 5,3 x 2)。 For those lists I end up getting a list index out of range error Code here: 对于那些列表,我最终得到一个列表索引超出范围错误代码在这里:

def symmetric(square):
    final_result = []
    x = 0
    y = 0
    while x < len(square):
        row_list = []
        col_list = []
        while y < len(square[x]):
            print "(x, y): %d, %d" % (x, y)
            print "(y, x): %d, %d" % (y, x)
            row_list.append(square[x][y])
            col_list.append(square[y][x])
            y = y + 1
        if row_list == col_list:
            final_result.append(True)
        else:
            final_result.append(False)
        x = x + 1

    for x in final_result:
        if x == False:
            return False
    return True

And the test cases that I'm failing on here: 我在这里失败的测试用例:

print symmetric([[1, 2, 3, 4],
                [2, 3, 4, 5],
                [3, 4, 5, 6]])
#Expected result: >>> False
#List index out of range

# This one actually returns the correct result, I'm just including it here
# for reference.
#print symmetric([["cat", "dog", "fish"],
#                ["dog", "dog", "fish"],
#                ["fish", "fish", "cat"]])
#Expected result: >>> True
#Actual result: >>> True


print symmetric([[1,2,3],
                 [2,3,1]])
#Expected Result: >>> False
#Actual result: list index out of range

Can someone help me modify the code so that it will work on these "irregularly shaped" arrays? 有人可以帮我修改代码,以便它可以在这些“不规则形状”的数组上工作吗?

This bit of code will do it all for you: 这段代码将为您完成所有操作:

def symmetric(square):
    square = [tuple(row) for row in square]
    return square == zip(*square)

In your solution you're doing too much of the work yourself. 在你的解决方案中,你自己做了太多的工作。 Python will compare sequences for you, so an easier method is to transpose the square so its rows become columns and vice versa and then compare it to the original value. Python将为您比较序列,因此更简单的方法是转换方块,使其行成为列,反之亦然,然后将其与原始值进行比较。

We can transpose the square using the zip function . 我们可以使用zip功能转置方块。 This takes a number of sequences and returns a tuple containing first of each and then a tuple with the second of each and so on. 这需要许多序列并返回一个包含每个序列的元组,然后是一个元组,每个元组包含第二个元组,依此类推。 By passing square as *square we pass each row as a sperate argument; 通过将square作为*square传递,我们将每一行作为sperate参数传递; this has the effect of transposing the square. 这具有转置广场的效果。

The only complication is that zip returns tuples not lists so we have to make sure square is a list of tuples so the comparison works. 唯一的复杂因素是zip返回元组而不是列表,因此我们必须确保square是一个元组列表,以便进行比较。

You can put this check at the start of your function: 您可以在功能开始时进行此检查:

for row in square:
    if len(row) != len(square):
        return False

Or maybe shorter 或者更短

if not all(len(square) == len(row) for row in square): return False

Here's an alternative version for the main test: 这是主要测试的替代版本:

for i, line in enumerate(matrix):
    for j in range(len(line)):
        if a[i][j] != a[j][i]:
             return False
return True

Of course that all the other answers that advise you to test if the matrix is square hold true. 当然,所有其他答案建议您测试矩阵是否为正方形。

Add this near the beginning: 在开头附近添加:

for row in square:
    if len(row) != len(square):
        return False

A version for Python3 Python3的一个版本

def symmetric(L)
    return all(i==j for i,*j in zip(L ,*L))

Value y = 0 should be inside the first while loop. y = 0应该在第一个while循环内。 Like this: 像这样:

def symmetric(square):
    final_result = []
    x = 0
    while x < len(square):
         y = 0
        row_list = []
        .
        .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM