Python - Algorithm to determine if a list is symmetric

前端 未结 6 1650
灰色年华
灰色年华 2021-01-22 00:01

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\"

相关标签:
6条回答
  • 2021-01-22 00:30

    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
    
    0 讨论(0)
  • 2021-01-22 00:31

    Add this near the beginning:

    for row in square:
        if len(row) != len(square):
            return False
    
    0 讨论(0)
  • 2021-01-22 00:31

    A version for Python3

    def symmetric(L)
        return all(i==j for i,*j in zip(L ,*L))
    
    0 讨论(0)
  • 2021-01-22 00:32

    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.

    0 讨论(0)
  • 2021-01-22 00:44

    Value y = 0 should be inside the first while loop. Like this:

    def symmetric(square):
        final_result = []
        x = 0
        while x < len(square):
             y = 0
            row_list = []
            .
            .
    
    0 讨论(0)
  • 2021-01-22 00:49

    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.

    We can transpose the square using the zip function. 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; 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.

    0 讨论(0)
提交回复
热议问题