3

So I have

A = [1,2,3,4]

I want to check if the array is symmetric. So the output would be False

Another example would be

arr = [1,2,3,3,2,1]
out = fun(arr)
out = True

I have been trying by like

def checksymm(a):
    flag = 0

    for i in range(0,len(a)/2):
        if np.abs(a[i]) == np.abs(a[-i]):
            return True
        else:
            return False

What can I be doing wrong? Thanks.

1
  • 4
    Why would you use np.abs here? Commented Feb 28, 2022 at 12:57

3 Answers 3

6

Corresponding of a[i] should be a[-1-i], not a[-i].

Besides, why not just reverse the list and compare each elements:

def isSymmetric(arr):
    return (arr == arr[::-1]).all()
Sign up to request clarification or add additional context in comments.

Comments

1

Probably the most efficient way would be to restrict the comparison to each half of the array:

n = len(arr) // 2
result = np.all(arr[:n] == arr[-1:-n - 1:-1])

With absolute values:

result = (np.abs(arr[:n]) == np.abs(arr[-1:-n - 1:-1])).all()

Both formulations should work directly with either lists or arrays.

Comments

0

When you compare, pay attention to the index, 0 with -1, 1 with -2 etc (not 1 with -1), so it should be i and -i-1 . Also instead of returning True after finding one equality , you should return after all of them are equal ...

arr = [1,2,3,3,2,1]

def checksymm(a):

    for i in range(0,len(a)//2):
        if a[i] != a[-i-1]: # or  np.abs(a[i]) != np.abs(a[-i-1]) as in the original code
            return False
    return True

    
out = checksymm(arr)
print(out)

>>> True

And :

arr = [1,2,3,3,5,1]
out = checksymm(arr)
print(out)

>>> False

Edit : I tried to find the problem with your code and fix it, but I would recommand the answer of @songziming it's better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.