Finding symmetric pairs in an array in Python

Symmetric pairs in array

In this program we will be finding symmetric pairs in an array in Python.Two pairs (a, b) and (c, d) are said to be symmetric if c is equal to b and a is equal to d.The input here is array containing pairs of elements and the output is symmetric pairs

Example : arr=[[5,7],[19,22],[13,15],[22,19],[7,5]]

[5,7],[7,5] and [19,22],[22,19] are symmetric pairs

[5,7] and [19,22] have symmetric pair

Symmetric pairs in an array

Approach: Finding symmetric pairs in an array in Python

The solution used here is hashing.The first element of pair is used as key and the second element is used as the value. The idea is to traverse all pairs one after other. For every pair, check if its second element is present in the hash table. If yes, then compare the first element with the value of the matched entry of the hash table. If the value and the first element match, then we have found the symmetric pairs. Else, insert the first element as a key and second element as value.

Python Code:

def findSymPairs(arrrow): 
    hM = dict() 
    for i in range(row): 
        first = arr[i][0
        sec = arr[i][1
        if (sec in hM.keys() and hM[sec] == first): 
            print(“(“, sec,“,”, first, “)”
        else
            hM[first] = sec 
arr=[]
n=int(input(“Enter the number of pairs”))
for i in  range(0,n):
    l=list(map(int,input().split()))
    arr.append(l)
print(“Symmetric elements are”)
findSymPairs(arr,n)

Output:

Enter the number of pairs 5
11 20
30 40
5 10
40 30
10 5
Symmetric elements are
(30 , 40)
(5  , 10)