Python - Ordered tuples extraction
Last Updated :
17 Apr, 2023
Given a tuple list, get all the tuples which are sorted in ascending order.
Input : test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (2, 5, 6), (9, 1)]
Output : [(3, 4, 6), (2, 5, 6)]
Explanation : Sorted tuples are extracted.
Input : test_list = [(5, 4, 6, 2, 4), (3, 4, 1), (2, 5, 4), (9, 1)]
Output : []
Explanation : No Sorted tuples.
Method #1 : Using list comprehension + sorted()
In this, we check if tuple is ordered using sorted(), and list comprehension is used to iterate for each tuple.
Python3
# Python3 code to demonstrate working of
# Ordered tuples extraction
# Using list comprehension + sorted()
# initializing list
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
# printing original list
print("The original list is : " + str(test_list))
# sorted() used to order, comparison operator to test
res = [sub for sub in test_list if tuple(sorted(sub)) == sub]
# printing result
print("Ordered Tuples : " + str(res))
OutputThe original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
Ordered Tuples : [(3, 4, 6), (9, 10, 34), (2, 5, 6)]
Time Complexity: O(nlogn), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using filter() + lambda + sorted()
In this, the task of filtering is done using filter(), sorted() fed to lambda for with comparison to get required result.
Python3
# Python3 code to demonstrate working of
# Ordered tuples extraction
# Using filter() + lambda + sorted()
# initializing list
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
# printing original list
print("The original list is : " + str(test_list))
# sorted() used to order, comparison operator to test
res = list(filter(lambda sub: tuple(sorted(sub)) == sub, test_list))
# printing result
print("Ordered Tuples : " + str(res))
OutputThe original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
Ordered Tuples : [(3, 4, 6), (9, 10, 34), (2, 5, 6)]
Method#3: Using Recursive method.
Python3
def ordered_tuples(test_list, result=[]):
if len(test_list) == 0:
return result
else:
first, *rest = test_list
if tuple(sorted(first)) == first:
result.append(first)
return ordered_tuples(rest, result)
# initializing list
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
# printing original list
print("The original list is : " + str(test_list))
# calling function to extract ordered tuples
res = ordered_tuples(test_list)
# printing result
print("Ordered Tuples : " + str(res))
#this code contributed by tvsk
OutputThe original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
Ordered Tuples : [(3, 4, 6), (9, 10, 34), (2, 5, 6)]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using all()
Step-by-step approach:
- Traverse through each character in the string.
- For each character, check if it is an opening parenthesis or closing parenthesis. If it is an opening parenthesis, push it to the stack. If it is a closing parenthesis, check if the stack is empty or the top of the stack is not the corresponding opening parenthesis for the closing parenthesis. If it is, return False.
- After traversing through the string, check if the stack is empty. If it is, return True. If it is not, return False.
Below is the implementation of the above approach:
Python3
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
# printing original list
print("The original list is : " + str(test_list))
# Using all() to filter ordered tuples
ordered_tuples = list(filter(lambda tup: all(tup[i] <= tup[i+1] for i in range(len(tup)-1)), test_list))
# Print the result
print("Ordered Tuples: ", ordered_tuples)
#This code is contributed by Vinay Pinjala.
OutputThe original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
Ordered Tuples: [(3, 4, 6), (9, 10, 34), (2, 5, 6)]
Time complexity: The time complexity of this approach is O(n), where n is the length of the input string. This is because we need to traverse through each character in the string once.
Auxiliary space: The auxiliary space complexity of this approach is O(n), where n is the length of the input string. This is because we need to store the opening parenthesis in the stack and the maximum size of the stack is equal to the length of the input string.
Method #5: Using the itertools.groupby() function:
Algorithm:
1.Import itertools module
2.Initialize an empty list ordered_tuples to store ordered tuples
3.Iterate over the groups returned by itertools.groupby() method, grouped based on whether each tuple satisfies the ordering condition
4.If a group contains only ordered tuples, extend the ordered_tuples list with the tuples in the group
5.Print the ordered_tuples list
Python3
import itertools
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
# printing original list
print("The original list is : " + str(test_list))
ordered_tuples = []
for k, g in itertools.groupby(test_list, lambda tup: all(tup[i] <= tup[i+1] for i in range(len(tup)-1))):
if k:
ordered_tuples.extend(g)
print("Ordered Tuples: ", ordered_tuples)
#This code is contributed by Jyothi pinjala.
OutputThe original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
Ordered Tuples: [(3, 4, 6), (9, 10, 34), (2, 5, 6)]
Time complexity: O(nlogn) where n is the total number of elements in all tuples. This is because the itertools.groupby() method and the all() function take O(n) time complexity, while the extend() method takes O(m) time complexity, where m is the number of elements in the group of ordered tuples. The total time complexity is dominated by the sorting that happens inside itertools.groupby(), which has a time complexity of O(nlogn).
Auxiliary Space: O(m) where m is the number of elements in the largest group of ordered tuples. This is because the itertools.groupby() method groups the input list into separate sublists, and the largest sublist needs to be stored in memory.
Method #6: Using map() and set()
Step-by-step approach:
- Define a list of tuples named "test_list" containing multiple tuples with different number of integers in each tuple.
- Create an empty list named "res".
- Iterate through each tuple "tup" in the "test_list".
- For each "tup", sort the integers using "sorted" function and convert the sorted integers into tuple using "tuple" function. Then, map the tuple of sorted integers to "map" function.
- Then, convert the output of "map" function to set using "set" function.
- Check if the set obtained in the previous step is equal to the set containing the original tuple "tup" using "==" operator.
- If the sets are equal, then the tuple "tup" is ordered. Append it to the list "res".
- After iterating through all tuples in the "test_list", print the list "res" containing all ordered tuples.
Below is the implementation of the above approach:
Python3
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
res = []
for tup in test_list:
if set(map(tuple, map(sorted, [tup]))) == {tup}:
res.append(tup)
print("Ordered Tuples: ", res)
OutputOrdered Tuples: [(3, 4, 6), (9, 10, 34), (2, 5, 6)]
Time complexity: O(nklog k)
Auxiliary space: O(n*k)
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