# Python program to sort tuples by frequency of their absolute difference

• Last Updated : 24 Jan, 2021

Given list of dual tuples, the task here is to write a python program that can sort them by frequency of their elements’ absolute difference.

Input : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)]

Output : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)]

Explanation : 7 – 5 = 2 occurs only 1 time. 5 occurs twice [( 6 – 1), (11 – 6)] and 8 occurs 3 times as difference.

Input : [(1, 6), (6, 11), (5, 7)]

Output : [(5, 7), (1, 6), (6, 11)]

Explanation : 7 – 5 = 2 occurs only 1 time. 5 occurs twice [( 6 – 1), (11 – 6)].

Method : Using sorted(), abs(), count() and list comprehension

In this, we perform task of computing each absolute difference using abs() and list comprehension. Then, sorted() and count() are used to sort tuples based on computed results of absolute difference.

Example:

## Python3

 # initializing listtest_list = [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)]  # printing original listprint("The original list is : " + str(test_list))  # getting differences pairsdiff_list = [abs(x - y) for x, y in test_list]  # sorting list by computed differencesres = sorted(test_list, key = lambda sub: diff_list.count(abs(sub[0] - sub[1])))  # printing resultprint("Sorted Tuples : " + str(res))

Output:

The original list is : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)]

Sorted Tuples : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)]

My Personal Notes arrow_drop_up