Python - Sort by range inclusion
Last Updated :
23 Apr, 2023
Given a range, sort tuple Matrix by total range covered in a given range. [Considering tuples which completely lie within range].
Input : test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]], i, j = 2, 15
Output : [[(3, 16)], [(1, 5), (6, 10), (10, 15)], [(1, 3), (9, 13)], [(2, 4), (6, 8), (9, 14)]]
Explanation : 0 < 4 < 4 < 9, is the magnitude of range covered in tuples lists.
Input : test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)]], i, j = 2, 15
Output : [[(3, 16)], [(1, 5), (6, 10), (10, 15)], [(2, 4), (6, 8), (9, 14)]]
Explanation : 0 < 4 < 9, is the magnitude of range covered in tuples lists.
Method #1 : Using sort() + sum()
In this, inplace sorting is performed using sort(), and summation of ranges in the given range is performed using sum() and list comprehension with conditions.
Python3
# Python3 code to demonstrate working of
# Sort by range inclusion
# Using sort() + sum()
def range_sum(row):
# summing in range element
return sum([abs(sub[1] - sub[0]) for sub in row if sub[0] > i and sub[0] < j and sub[1] > i and sub[1] < j])
# initializing list
test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [
(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 15
# inplace sorting using sort()
test_list.sort(key=range_sum)
# printing result
print("Sorted List : " + str(test_list))
Output:
The original list is : [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]] Sorted List : [[(3, 16)], [(1, 5), (6, 10), (10, 15)], [(1, 3), (9, 13)], [(2, 4), (6, 8), (9, 14)]]
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Method #2 : Using sorted() + lambda + sum()
In this, we perform task of sorting using sorted() and utility injection using lambda function, the summation is performed using sum().
Python3
# Python3 code to demonstrate working of
# Sort by range inclusion
# Using sorted() + lambda + sum()
# initializing list
test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [
(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 15
# sorting using sorted() + lambda
res = sorted(test_list, key=lambda row: sum(
[abs(sub[1] - sub[0]) for sub in row if sub[0] > i and sub[0] < j and sub[1] > i and sub[1] < j]))
# printing result
print("Sorted List : " + str(res))
Output:
The original list is : [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]] Sorted List : [[(3, 16)], [(1, 5), (6, 10), (10, 15)], [(1, 3), (9, 13)], [(2, 4), (6, 8), (9, 14)]]
Time Complexity: O(n*logn), where n is the length of the input list. This is because we’re using the built-in sorted() function which has a time complexity of O(nlogn) in the worst case.
Auxiliary Space: O(1), as we’re not using any additional space other than the input list itself.
METHOD 3:Using filter() function and Sorting
APPROACH:
we use the filter() function to create a new list based on the range inclusion of each sublist. Then we sort the sublists based on their range inclusion.
ALGORITHM:
1.Start by defining the input variables test_list, i, and j.
2.Use the filter() function to iterate through each tuple in the test_list and check if any of the values in the tuple fall within the range [i,j].
3.Use the sorted() function to sort the filtered list by whether each tuple contains a value within the range [i,j]. Sort the list in reverse order so that tuples that contain values within the range [i,j] are first.
4.Print the sorted list.
Python3
test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
i, j = 2, 15
filtered_list = list(filter(lambda x: any(i <= a <= j or i <= b <= j for a, b in x), test_list))
sorted_list = sorted(filtered_list, key=lambda x: any(i <= a <= j or i <= b <= j for a, b in x), reverse=True)
print(sorted_list)
Output[[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
Time Complexity: O(N*log(N)), where N is the number of sublists.
Space Complexity: O(N), where N is the number of sublists.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â 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.Python is:A high-level language, used in web development, data science, automatio
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
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
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
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
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