Python - Algorithm To Determine If A List Is Symmetric
Solution 1:
This bit of code will do it all for you:
defsymmetric(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.
Solution 2:
You can put this check at the start of your function:
for row in square:
iflen(row) != len(square):
returnFalseOr maybe shorter
ifnotall(len(square) == len(row) for row in square): returnFalseSolution 3:
Here's an alternative version for the main test:
for i, line inenumerate(matrix):
for j inrange(len(line)):
if a[i][j] != a[j][i]:
returnFalsereturnTrueOf course that all the other answers that advise you to test if the matrix is square hold true.
Solution 4:
Add this near the beginning:
for row in square:
iflen(row) != len(square):
returnFalseSolution 5:
A version for Python3
defsymmetric(L)
returnall(i==j for i,*j inzip(L ,*L))
Post a Comment for "Python - Algorithm To Determine If A List Is Symmetric"