Home > Blockchain >  How do I return true, for two arrays that are the same length and value? (Python)
How do I return true, for two arrays that are the same length and value? (Python)

Time:12-02

So, the question I am trying to solve is...

"Return true if two arrays are equal.

The arrays are equal if they are the same length and contain the same value at each particular index.

Two empty arrays are equal."

for example:

input:

a == [1, 9, 4, 6, 3]
b == [1, 9, 4, 6, 3]

output: 
true

OR 

input:
a == [5, 3, 1]
b == [6, 2, 9, 4]

output:
false

This is how I went about it. I'm able to get the length of the arrays right, but I don't know how to ensure the values in it will be the same too. That's the part I am stuck on how to implement.

def solution(a, b):
    if range(len(a)) == range(len(b)): 
        return True
    else: 
        return False

CodePudding user response:

Use numpy.array_equal:

a = [1, 9, 4, 6, 3]
b = [1, 9, 4, 6, 3]
np.array_equal(a, b)
# True

a = [5, 3, 1]
b = [6, 2, 9, 4]
np.array_equal(a, b)
# False

np.array_equal([], [])
# True

CodePudding user response:

just use a for loop

def solution(a, b):
    x = 0
    if (len(a) == len(b)): 
        for i in range(len(a)):
            if (a[i] == b[i]):
                x = 1
            else:
                x = 0
                break
        if (x==1):
            return True
        else:
            return False
    else: 
        return False
  • Related