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 - Sort Dictionaries by Size
Given a Dictionary List, perform sort by size of dictionary. Input : test_list = [{4:6, 9:1, 10:2, 2:8}, {4:3, 9:1}, {3:9}, {1:2, 9:3, 7:4}] Output : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}] Explanation : 1 < 2 < 3 < 4, sorted by number of keys of dictionary. In
4 min read
Sort a list in python
Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting.Python# Initializing a list a = [5, 1, 5, 6] # Sort modifies the given list a.sort() print(a) b = [5, 2, 9, 6] # Sorted does not modify the gi
5 min read
Sort a Dictionary - Python
In Python, dictionaries store key-value pairs and are great for organizing data. While they werenât ordered before Python 3.7, you can still sort them easily by keys or values, in ascending or descending order. Whether youâre arranging names alphabetically or sorting scores from highest to lowest, P
5 min read
Python - Sort Records by Kth Index List
Sometimes, while working with Python Records, we can have a problem in which we need to perform Sorting of Records by some element in Tuple, this can again be sometimes, a list and sorting has to performed by Kth index of that list. This is uncommon problem, but can have usecase in domains such as w
4 min read
Sort Python Dictionary by Value
Python dictionaries are versatile data structures that allow you to store key-value pairs. While dictionaries maintain the order of insertion. sorting them by values can be useful in various scenarios. In this article, we'll explore five different methods to sort a Python dictionary by its values, a
3 min read
Python - Sort Matrix by Row Median
Given a Matrix, sort by median of each row. Input : test_list = [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]] Output : [[1, 7, 2], [3, 4, 7], [10, 2, 4], [8, 6, 5]] Explanation : 2 < 3 < 4 < 6, sorted increasingly by median element. Input : test_list = [[3, 4, 7], [1, 7, 2], [8, 6, 5]] Outp
4 min read
Python JSON Sort
In the world of programming, managing and manipulating data is a fundamental task. JSON (JavaScript Object Notation) is a widely used data interchange format due to its simplicity and human-readable structure. When working with JSON data in Python, sorting becomes essential for better organization a
3 min read
Python - Extract Missing Ranges
Given list of tuples, start range and end range values, extract the ranges that are missing from the list. Input : test_list = [(7, 2), (15, 19), (38, 50)], strt_val = 5, stop_val = 60 Output : [(5, 7), (2, 60), (2, 15), (19, 60), (19, 38), (50, 60)] Explanation : Missing element ranges starting fro
2 min read
Cycle Sort - Python
Cycle sort is an in-place, unstable sorting algorithm that is particularly useful when sorting arrays containing elements with a small range of values.It is optimal in terms of several memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if itâs a
3 min read
Python | Find missing numbers in a sorted list range
Given a range of sorted list of integers with some integers missing in between, write a Python program to find all the missing integers. Examples: Input : [1, 2, 4, 6, 7, 9, 10] Output : [3, 5, 8] Input : [5, 6, 10, 11, 13] Output : [7, 8, 9, 12] Method #1: List comprehension Python # Python3 progra
5 min read