Home > Software design >  Symmetric 1D array Python
Symmetric 1D array Python

Time:03-01

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.

CodePudding user response:

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()

CodePudding user response:

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.

CodePudding user response:

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.

  • Related