Note that there are some explanatory texts on larger screens.

plurals
  1. POPython - Algorithm to determine if a list is symmetric
    text
    copied!<p>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. The goal is to have a function that returns the boolean True if its symmetric, and False if its not.</p> <p>I've managed to write a function that works, but it only work on lists whose sizes are perfect squares, (e.g 2 x 2, 4 x 4), and a few of my test cases are of "irregular" sizes (e.g 2 x 5, 3 x 2). For those lists I end up getting a list index out of range error Code here:</p> <pre><code>def symmetric(square): final_result = [] x = 0 y = 0 while x &lt; len(square): row_list = [] col_list = [] while y &lt; 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 </code></pre> <p>And the test cases that I'm failing on here:</p> <pre><code>print symmetric([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]) #Expected result: &gt;&gt;&gt; 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: &gt;&gt;&gt; True #Actual result: &gt;&gt;&gt; True print symmetric([[1,2,3], [2,3,1]]) #Expected Result: &gt;&gt;&gt; False #Actual result: list index out of range </code></pre> <p>Can someone help me modify the code so that it will work on these "irregularly shaped" arrays?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload