Python program to count Bidirectional Tuple Pairs

PythonServer Side ProgrammingProgramming

When it is required to count the number of bidirectional tuple pairs in a list of tuples, the list can be iterated over using nested loops, and the ‘AND’ operation is performed on the first element and result of equality between first and second element.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [(45, 67), (11, 23), (67, 45), (23, 11), (0, 9), (67, 45)]

print("The list is : ")
print(my_list)

my_result = 0
for idx in range(0, len(my_list)):
   for iidx in range(idx + 1, len(my_list)):
      if my_list[iidx][0] == my_list[idx][1] and my_list[idx][1] == my_list[iidx][0]:
         my_result += 1

print("The count of bidirectional pairs are : ")
print(my_result)

Output

The list is :
[(45, 67), (11, 23), (67, 45), (23, 11), (0, 9), (67, 45)]
The count of bidirectional pairs are :
3

Explanation

  • A list of tuples is defined, and is displayed on the console.

  • A result variable is assigned to 0.

  • The list is iterated over twice.

  • The ‘AND’ operation is performed between two elements.

  • The first element and the result of equality check between second and first elements.

  • Now, the result variable is incremented.

  • This result is displayed on the console.

raja
Published on 15-Apr-2021 12:57:10
Advertisements