Python program to count Bidirectional Tuple Pairs
Last Updated :
08 May, 2023
Given Tuple list, compute bidirectional tuples.
Input : test_list = [(5, 6), (1, 2), (6, 5), (9, 1), (6, 5), (2, 1)]
Output : 3
Explanation : (1, 2), (2, 1); (5, 6) -> [(6, 5), (6, 5)], total 3 pairs.
Input : test_list = [(5, 6), (1, 3), (6, 5), (9, 1), (6, 5), (2, 1)]
Output : 2
Explanation : (5, 6) -> [(6, 5), (6, 5)], total 2 pairs.
Method 1: Using loop
In this we check for each element if we have any other element which is bidirectional, Once the pair is found, counter is incremented.
Python3
# Python3 code to demonstrate working of
# Count Bidirectional Tuple Pairs
# Using loop
# initializing list
test_list = [(5, 6), (1, 2), (6, 5), (9, 1), (6, 5), (2, 1)]
# printing original list
print("The original list is : " + str(test_list))
res = 0
for idx in range(0, len(test_list)):
for iidx in range(idx + 1, len(test_list)):
# checking bidirection
if test_list[iidx][0] == test_list[idx][1] and test_list[iidx][1] == test_list[idx][0]:
res += 1
# printing result
print("Bidirectional pairs count : " + str(res))
OutputThe original list is : [(5, 6), (1, 2), (6, 5), (9, 1), (6, 5), (2, 1)]
Bidirectional pairs count : 3
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method 2: Using a dictionary
Step-by-step approach:
- Initialize an empty dictionary to store the frequency of each tuple.
- Populate the dictionary with the frequency of each tuple using a loop.
- Count the bidirectional pairs by iterating over the dictionary. For each tuple in the dictionary, we check if its reverse tuple is also in the dictionary. If it is, we add the product of their frequencies to the result.
- Divide the result by 2 to account for bidirectional pairs being counted twice.
- Print the final result.
Python3
# initializing list
test_list = [(5, 6), (1, 2), (6, 5), (9, 1), (6, 5), (2, 1)]
# initializing an empty dictionary
freq_dict = {}
# populating the dictionary with frequency of each tuple
for tup in test_list:
freq_dict[tup] = freq_dict.get(tup, 0) + 1
# counting the bidirectional pairs
res = 0
for tup, freq in freq_dict.items():
reverse_tup = (tup[1], tup[0])
if reverse_tup in freq_dict:
res += freq * freq_dict[reverse_tup]
# dividing by 2 to account for bidirectional pairs counted twice
res //= 2
# printing result
print("Bidirectional pairs count : " + str(res))
OutputBidirectional pairs count : 3
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n) to store the dictionary.
Method 3 : uses the built-in Counter class from the collections module
step-by-step approach
- Import the Counter class from the collections module.
- Initialize a list of tuples called "test_list". This list contains the tuples for which we want to find the bidirectional pairs.
- Create a Counter object by passing the "test_list" as an argument to the Counter() function. The Counter object will count the frequency of each tuple in the "test_list".
- Initialize a variable called "res" to 0. This variable will store the count of bidirectional pairs.
- Use a for loop to iterate over the tuples and their frequencies in the Counter object.
- Inside the for loop, create a tuple called "reverse_tup" by reversing the current tuple using the reversed() function and passing it to the tuple() constructor.
- Check if the "reverse_tup" exists in the Counter object.
- If "reverse_tup" exists in the Counter object, add the product of the frequency of the current tuple and the frequency of the reverse tuple to the "res" variable.
- After the for loop, divide the "res" variable by 2 to account for bidirectional pairs counted twice.
- Print the final count of bidirectional pairs.
Python3
from collections import Counter
# initializing list
test_list = [(5, 6), (1, 2), (6, 5), (9, 1), (6, 5), (2, 1)]
# counting the frequency of each tuple
counter = Counter(test_list)
# counting the bidirectional pairs
res = 0
for tup, freq in counter.items():
reverse_tup = tuple(reversed(tup))
if reverse_tup in counter:
res += freq * counter[reverse_tup]
# dividing by 2 to account for bidirectional pairs counted twice
res //= 2
# printing result
print("Bidirectional pairs count: " + str(res))
OutputBidirectional pairs count: 3
The time complexity of this solution is O(n), since we only need to loop over the list once and do constant-time lookups in the Counter.
The space complexity is also O(n), since we need to store the frequency of each tuple in the Counter.
Similar Reads
Python | Program to count duplicates in a list of tuples Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicates exist, print the number of occurrences of each duplicate tuple, otherwise print "No Duplicates". Examples: Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] Output : ('a
6 min read
Python List and Tuple Combination Programs Lists and tuples are two of the most commonly used data structures in Python. While lists are mutable and allow modifications, tuples are immutable and provide a stable structure for storing data. This article explores various programs related to list and tuple combinations, covering topics like:Sor
6 min read
Python - Pairwise Addition in Tuples Sometimes, while working with data, we can have a problem in which we need to find cumulative result. This can be of any type, product or summation. Here we are gonna discuss about adjacent element addition. Letâs discuss certain ways in which this task can be performed. Method #1 : Using zip() + ge
4 min read
Convert List of Dictionary to Tuple list Python Given a list of dictionaries, write a Python code to convert the list of dictionaries into a list of tuples.Examples: Input: [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] Output: [('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)] Below are various methods to co
5 min read
Python Program for Count pairs with given sum Given an array of integers, and a number 'sum', find the number of pairs of integers in the array whose sum is equal to 'sum'. Examples: Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : 3 Pairs with sum 6 are
3 min read
Python | Test if tuple is distinct Sometimes, while working with records, we have a problem in which we need to find if all elements of tuple are different. This can have applications in many domains including web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is a brute force
4 min read