Python Program to Check If two Arrays are Same or Not

Check If two Arrays are Same or Different

 

In this section, we will learn how to Check the Equality of two arrays using Python.

Two arrays are equal if both arrays have the same length of elements and all the elements of one array are the same as in the second array. The arrangement of elements may be different in the arrays but the value of the elements will be the same.

Check If two Arrays are Same or Not

Algorithm

  • Take Size of 1st array (n1), elements of 1st array (arr1), size of 2nd array (n2) and elements of 2nd array (arr2) as input from user
  • Calling function checkEqual(arr1,arr2,n1,n2) in if condition
  • If the function returns True then print Both the arrays are Equal
  • Else print Arrays are not Equal
checkEqual (arr1, arr2, n1, n2 ) :
  1. Compare the length of both the arrays if both have different arrays then return false
  2. Else sort both the arrays
  3. Traverse each index of the both the arrays
  4. Compare same index elements, if elements are different return False else return True
  5. If none of the above conditions satisfied return True.

Python Code

 
#function to check whether both the arrays are equal or not
def checkEqual(arr1,arr2,n1,n2):
    #if the length of arrays are different return false
    if n1!=n2:
        return False
    else:
        #sort both the arrays
        arr1.sort()
        arr2.sort()
        #traverse each index of arrays
        for i in range(n1):
            #for same index if the value in the sorted arrays are different return false
            if arr1[i]!=arr2[i]:
                return False
    #if none of the above conditions satisfied return true
    return True
 
#inputs form user
n1=int(input(“Enter the size of 1st Array : “))
arr1=list(map(int,input(“Enter the elements of 1st Array : “).split()))
n2=int(input(“Enter the size of 2nd Array : “))
arr2=list(map(int,input(“Enter the elements of 2nd Array : “).split()))
 
#if function returns true then print arrays are equal
if checkEqual(arr1,arr2,n1,n2):
    print(\nBoth the Arrays are Equal”)
#if function reutrns false then print arrays are not equal
else:
    print(\nArrays are not Equal”)
   
Output :

TEST CASE 1

Enter the size of 1st Array : 5
Enter the elements of 1st Array : 1 2 3 4 5
Enter the size of 2nd Array : 6
Enter the elements of 2nd Array : 5 6 4 5 6 4

Arrays are not Equal


TEST CASE 2

nter the size of 1st Array : 5
Enter the elements of 1st Array : 1 5 4 2 3
Enter the size of 2nd Array : 5
Enter the elements of 2nd Array : 1 2 3 5 4

Both the Arrays are Equal