Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to count Bidirectional Tuple Pairs
When it is required to count the number of bidirectional tuple pairs in a list of tuples, we can iterate over the list using nested loops and check if pairs are reverse of each other. A bidirectional pair means if we have tuple (a, b), there exists another tuple (b, a) in the list.
Below is a demonstration of the same ?
Example
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][0] == my_list[iidx][1]:
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
How It Works
The algorithm compares each tuple with every other tuple that comes after it in the list. For each pair of tuples, it checks if they are bidirectional by verifying:
The first element of the first tuple equals the second element of the second tuple
The second element of the first tuple equals the first element of the second tuple
In our example:
(45, 67)and(67, 45)form a bidirectional pair(11, 23)and(23, 11)form a bidirectional pair(67, 45)appears twice, so it forms another pair with(45, 67)
Alternative Approach Using Set
We can also use a set-based approach for better efficiency:
my_list = [(45, 67), (11, 23), (67, 45), (23, 11), (0, 9), (67, 45)]
print("The list is : ")
print(my_list)
my_result = 0
seen = set()
for tuple_item in my_list:
reverse_tuple = (tuple_item[1], tuple_item[0])
if reverse_tuple in seen:
my_result += 1
seen.add(tuple_item)
print("The count of bidirectional pairs are : ")
print(my_result)
The list is : [(45, 67), (11, 23), (67, 45), (23, 11), (0, 9), (67, 45)] The count of bidirectional pairs are : 3
Conclusion
Both approaches successfully count bidirectional tuple pairs. The nested loop approach is straightforward but has O(n²) complexity, while the set-based approach is more efficient with O(n) complexity for large datasets.
