0

Most of my test cases are returning correct results but one this one is returning True when it should be false:

print antisymmetric([[0, 1, 2], 
                 [-1, 0, -2], 
                 [2, 2,  3]])

Can anyone tell me what's wrong with my code? Thanks!

def antisymmetric(A):
    n = len(A)
    i = 0
    while i < n:
        j = 0
        while j < n:
            if A[i][j] == -A[j][i]:
                return True
            else:
                return False
            j += 1
        i += 1
# Test Cases:

print antisymmetric([[0, 1, 2], 
                 [-1, 0, 3], 
                 [-2, -3, 0]])
#>>> True

print antisymmetric([[0, 0, 0],
                 [0, 0, 0],
                 [0, 0, 0]])
#>>> True

print antisymmetric([[0, 1, 2], 
                 [-1, 0, -2], 
                 [2, 2,  3]])
#>>> False

print antisymmetric([[1, 2, 5],
                 [0, 1, -9],
                 [0, 0, 1]])
#>>> False
stamaimer
  • 6,227
  • 5
  • 34
  • 55
sim
  • 127
  • 2
  • 5
  • 13
  • which test case you considering as wrong? the result you wrote is actual result or desire result? – Gahan Apr 25 '18 at 04:06
  • 1
    The problem here is that you are always returning as soon as you compare the very first element. That means you never compare any of the other elements. If you don't understand why that's a problem, see [this question](https://stackoverflow.com/questions/5864166/return-statement-in-for-loops), which has a few different answers that explain it at different levels. – abarnert Apr 25 '18 at 04:23
  • 1
    As a side note, using a `while` loop and explicit `+= 1` is almost never necessary in Python. You can just for `for i in range(n):` and `for j in range(n)`. – abarnert Apr 25 '18 at 04:24

2 Answers2

1

You should return False as soon as possible and return True at the end of outer while loop to make sure all pair of value be compared.

stamaimer
  • 6,227
  • 5
  • 34
  • 55
1
def antisymmetric(l):
    for i in range(len(l)):
        for j in range(len(l[i])):
            if l[i][j] != -l[j][i] and i != j:
                return False
    return True

To evaluate if matrix is antisymmetric you need to check all the cases hence you should check negative condition that for any element if test not satisfies it immediately return False

In case of anti-symmetric it will evaluates all test cases and as shown in above example function will return True if for loop ends.

Your test result is failing because you are immediately returning True after matching one condition only. your loop will match i=0, j=0 as A[0][0] which is 0 and 0 == -0 will evaluate True and you immediately returned it hence it's giving you unwanted result.

Also you need to skip diagonal element because it doesn't changes

Gahan
  • 4,075
  • 4
  • 24
  • 44