Home »
Python »
Python programs
Python program to sort tuples by frequency of their absolute difference
In this program, we have a list of tuples and we need to sort the tuples of the list based on the frequency of their absolute difference in Python programming language.
Submitted by Shivang Yadav, on July 16, 2021
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.
Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].
Example:
list = [3 ,1, 5, 7]
A list of tuples is a list whose each element is a tuple.
Example:
upList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]
Sorting tuples by frequency of their absolute difference
We will be sorting all the tuples of the list based on the absolute difference of the elements of the tuples. We will put tuples with a single frequency of absolute difference 1 than 2 and so on.
Input:
[(4,6), (1, 3), (6, 8), (4, 1), (5, 2)]
Output:
[(4, 1), (5, 2), (4, 6), (1, 3), (6, 8)]
We need to find the absolute difference of all elements of the tuple and count the frequency occurrence of the absolute difference and sort the list accordingly.
A way to sort the list of tuples using absolute difference is by first computing the absolute difference of each tuple using the abs() method. Then sorting the tuples using the sorted() method and the count() method to sort the tuples based on the absolute difference count.
Program:
# Python program to sort tuples by frequency of
# their absolute difference
tupList = [(4,6), (1, 3), (6, 8), (4, 1), (5, 2)]
print("Tuple list before sorting : " + str(tupList))
# Sorting Tuple list
absList = [abs(x - y) for x, y in tupList]
sortedTupList = sorted(tupList, key = lambda sub: absList.count(abs(sub[0] - sub[1])))
# print resulting list
print("Tuple list before sorting : " + str(sortedTupList))
Output:
Tuple list before sorting : [(4, 6), (1, 3), (6, 8), (4, 1), (5, 2)]
Tuple list before sorting : [(4, 1), (5, 2), (4, 6), (1, 3), (6, 8)]
Python Tuple Programs »