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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read