Q:

Python program to sort tuples by frequency of their absolute difference

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to remove duplicate tuples irrespec... >>
<< Python program to sort a list of tuples in increas...