Python Programming: Is a List Symmetric Square

Python Programming: Is a List Symmetric Square

The problem, discussed here is from ‘Udacity‘s ‘Introduction To Programming With Python’ course. This specific problem will be found in lesson 13 quiz 2. This is an optional problem set, so they don’t provide the solution for this problem. I took this course to learn python. This is an excellent course for beginners. It helped me learn all the basics and gave me a very strong base. They have problem sets that students can try to solve. But solution is available in the course if any student is unable to solve it. Also there are optional problem sets. They are a bit harder than regular problem sets. It’s a good practice to try them out. But solution is not available in the course. This problem is one the quiz from an optional problem set. 

Problem

“A list is symmetric if the first row is the same as the first column, the second row is the same as the second column and so on. Write a procedure, symmetric, which takes a list as input, and returns the boolean True if the list is symmetric and False if it is not.”

Solution

First check if the list is empty. If the list is empty, it is obviously symmetric. Next, check if the number of rows and number of columns are the same. If not, then it should return false. If number of column and number of rows are the same then it’s turn to check if they are symmetric. For that, let’s initiate two variables. One will go through the columns and one will go through the rows. Here is how the code will look like:

def symmetric(p):

    # Your code here

    n = len(p)

    if p == []:

        return True

    i = 0

    if n != len(p[0]):

        return False

    while i <= n-1:

        j = 0

        while j <= n-1:

            if p[i][j] != p[j][i]:

                return False

            j = j + 1

        i = i + 1

    return True

Here are some test cases,that can be used to test this code.  

print symmetric([[1, 2, 3],

                 [2, 3, 4],

                 [3, 4, 1]])

#>>> True

 

print symmetric([[“cat”, “dog”, “fish”],

                [“dog”, “dog”, “fish”],

                [“fish”, “fish”, “cat”]])

#>>> True

 

print symmetric([[“cat”, “dog”, “fish”],

                [“dog”, “dog”, “dog”],

                [“fish”,”fish”,”cat”]])

#>>> False

 

print symmetric([[1, 2],

                [2, 1]])

#>>> True

 

print symmetric([[1, 2, 3, 4],

                [2, 3, 4, 5],

                [3, 4, 5, 6]])

#>>> False

 

print symmetric([[1,2,3],

                 [2,3,1]])

 

 

Hope, this was a helpful post. If anybody has done this more efficiently, please share. 

Leave a Reply

Close Menu