1

Possible Duplicate:
Python - Algorithm to determine if a list is symmetric

I need help writing a Python function - symmetric,that takes as input a list of size n(which is a square matrix) that checks the first row is the same as the first column, the second row is the same as the second column and so on, and returns boolean True if the elements are the same and false if they are not. The list could contain integers or strings.

def symmetric(my_list):

my_list = [[1, 2, 3],
           [2, 3, 4],
           [3, 4, 1]]
Community
  • 1
  • 1
Fadyboy
  • 107
  • 1
  • 2
  • 11

2 Answers2

4

This works in Python2

my_list == map(list, zip(*my_list))

zip(*some_2d_list) is a fairly well known idiom, when some_2d_list is unpacked and processed by zip it has the effect of transposing the rows and columns

Unfortunately zip returns a list of tuples, so it is necessary to convert those to lists. This is what map(list, ...) does

It may appear wasteful as testing for equality will compare each pair that are not on the diagonal twice, but this is done at the C level, so will be much faster than using explicit loops and doing the minimum number of comparisons.

If it is homework, I'd suggest that you should probably use nested loops

EDIT: In Python3, map(...) returns a map object, you can get the Python2 behaviour by using list(map(...))

EDIT: I think in Python3, this is better

all(i==j for i,*j in zip(my_list ,*my_list))
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0
import numpy as np
# convert the 2d list into an ndarry
x = np.array(my_list)
# test if x is identical to its transpose
isSymmetric = (x.T == x).all()

isSymmetric then tells you the result.

nye17
  • 12,857
  • 11
  • 58
  • 68