Python - Remove Equilength and Equisum Tuple Duplicates
Last Updated :
02 May, 2023
Sometimes, while working with Python tuples, we can have a problem in which we need to remove duplicates on basis of equal length and equal sum. This kind of problem can also be broken to accommodate any one of the required conditions. This kind of problem can occur in data domains and day-day programming. Let's discuss certain ways in which this task can be performed.
Input : test_list = [(1, 2, 0), (3, 0), (2, 1)]
Output : [(1, 2, 0), (3, 0)]
Input : test_list = [(1, 2, 0), (3, 0, 0), (0, 2, 1)]
Output : [(1, 2, 0)]
Method #1: Using nested loops
This is one of the ways in which this task can be performed. This is the brute force method, in which we loop for each tuple, a matching tuple w.r.t size and sum, and perform the removal.
Python3
# Python3 code to demonstrate working of
# Remove Equilength and Equisum Tuple Duplicates
# Using nested loop
# initializing lists
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# printing original list
print("The original list is : " + str(test_list))
# Remove Equilength and Equisum Tuple Duplicates
# Using nested loop
res = []
for sub in test_list:
for sub1 in res:
if len(sub) == len(sub1) and sum(sub) == sum(sub1):
break
else:
res.append(sub)
# printing result
print("Tuples after filtration : " + str(res))
OutputThe original list is : [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
Tuples after filtration : [(4, 5, 6), (3, 0), (1, 2, 3)]
Time complexity: O(n^2), where n is the length of the input list. This is because the program has a nested loop, where each element of the input list is compared with each element of the result list.
Auxiliary space: O(n), where n is the length of the input list. This is because the program creates a new list to store the filtered tuples, which can be at most the same length as the input list.
Method #2 : Using dict() + values()
The combination of the above functions offers another way to solve this problem. In this, we just harness the property of the dictionary of having unique keys and create a tuple key with len and sum of tuples. The duplicates are thus, avoided.
Python3
# Python3 code to demonstrate working of
# Remove Equilength and Equisum Tuple Duplicates
# Using dict() + values()
# initializing lists
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# printing original list
print("The original list is : " + str(test_list))
# Remove Equilength and Equisum Tuple Duplicates
# Using dict() + values()
res = list({(len(sub), sum(sub)): sub for sub in test_list}.values())
# printing result
print("Tuples after filtration : " + str(res))
OutputThe original list is : [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
Tuples after filtration : [(5, 5, 5), (2, 1), (1, 2, 3)]
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(m), where m is the number of unique tuples in the input list.
Method #3: Removing Equilength and Equisum Tuple Duplicates is to use a set to keep track of unique tuples.
One alternative method to solve the problem of removing Equilength and Equisum Tuple Duplicates is to use a set to keep track of unique tuples. For each tuple in the input list, we can create a new tuple that consists of its length and sum, and check if it already exists in the set. If it does not exist, we add the original tuple to the output list and add the new tuple to the set.
Python3
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# using a set to keep track of unique tuples
seen = set()
res = []
for t in test_list:
# create a new tuple that consists of length and sum
key = (len(t), sum(t))
# check if the new tuple is already in the set
if key not in seen:
# add the original tuple to the output list
res.append(t)
# add the new tuple to the set
seen.add(key)
print(res)
Output[(4, 5, 6), (3, 0), (1, 2, 3)]
Time complexity: O(n), where n is the length of the input list,
Auxiliary space: O(n), since we may need to store all n tuples in the output list and n unique (length, sum) tuples in the set.
Method #4: Using list comprehensions and lambda functions
This code snippet creates a lambda function compute_key to compute the length and sum of a tuple. It then uses a list comprehension to generate a new list res with unique tuples. The if condition in the list comprehension checks whether the computed key of the current tuple is already present in the keys of the computed keys of the previous tuples. If it's not present, the current tuple is added to the output list.
Python3
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# create a lambda function to compute the length and sum of a tuple
compute_key = lambda x: (len(x), sum(x))
# use list comprehension to generate a new list with unique tuples
res = [x for i, x in enumerate(test_list) if compute_key(x) not in map(compute_key, test_list[:i])]
print(res)
Output[(4, 5, 6), (3, 0), (1, 2, 3)]
Time complexity: O(n^2) because it uses a list comprehension with an enumerate function to iterate over each tuple in the input list and a map function to compute the keys of the previous tuples.
Auxiliary space: O(n) because it uses a new list res to store the unique tuples.
Method #5: Using a dictionary and tuple manipulation
This method involves using a dictionary to keep track of unique tuples based on their length and sum. The tuples are first converted to a string and then used as keys in the dictionary. If a tuple with the same length and sum is encountered, it is not added to the final list. Otherwise, the tuple is added to the dictionary and the final list.
Python3
# Python3 code to demonstrate working of
# Remove Equilength and Equisum Tuple Duplicates
# Using dictionary and tuple manipulation
# initializing lists
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# printing original list
print("The original list is : " + str(test_list))
# Remove Equilength and Equisum Tuple Duplicates
# Using dictionary and tuple manipulation
unique_tuples = {}
res = []
for tup in test_list:
tup_str = str(sorted(tup))
tup_len = len(tup)
tup_sum = sum(tup)
if tup_str not in unique_tuples:
unique_tuples[tup_str] = (tup_len, tup_sum)
res.append(tup)
# printing result
print("Tuples after filtration : " + str(res))
OutputThe original list is : [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
Tuples after filtration : [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
Time complexity: O(nlogn), where n is the number of tuples in the input list.
Auxiliary space: O(n), where n is the number of tuples in the input list.
Method #6 using itertools.groupby()
Python3
import itertools
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# sort the list by length and then by sum
test_list.sort(key=lambda x: (len(x), sum(x)))
# use itertools.groupby() to group tuples with the same length and sum
res = [next(group) for _, group in itertools.groupby(test_list, key=lambda x: (len(x), sum(x)))]
print(res)
Output[(3, 0), (1, 2, 3), (4, 5, 6)]
Time complexity: O(n*logn) because of the sorting operation.
Auxiliary space: O(n) space to store the output list.
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