
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to sort array by increasing frequency of elements in Python
Suppose we have an array with some elements where elements may appear multiple times. We have to sort the array such that elements are sorted according to their increase of frequency. So which element appears less number of time will come first and so on.
So, if the input is like nums = [1,5,3,1,3,1,2,5], then the output will be [2, 5, 5, 3, 3, 1, 1, 1]
To solve this, we will follow these steps −
mp := a new map
for each distinct element i from nums, do
x:= number of i present in nums
if x is present in mp, then
insert i at the end of mp[x]
otherwise mp[x] := a list with only one element i
ans:= a new list
for each i in sort the mp based on key, do
for each j in sort the list mp[i] in reverse order, do
insert j, i number of times into ans
return ans
Example (Python)
Let us see the following implementation to get better understanding −
def solve(nums): mp = {} for i in set(nums): x=nums.count(i) try: mp[x].append(i) except: mp[x]=[i] ans=[] for i in sorted(mp): for j in sorted(mp[i], reverse=True): ans.extend([j]*i) return ans nums = [1,5,3,1,3,1,2,5] print(solve(nums))
Input
[1,5,3,1,3,1,2,5]
Output
[2, 5, 5, 3, 3, 1, 1, 1]
- Related Articles
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Python program to sort tuples in increasing order by any key.
- Sorting array of Number by increasing frequency JavaScript
- Python program to sort tuples by frequency of their absolute difference
- Sort Tuples in Increasing Order by any key in Python program
- Python – Sort by Uppercase Frequency
- Python program to sort the elements of an array in ascending order
- Python program to sort the elements of an array in descending order
- Python - Sort rows by Frequency of K
- Python – Sort Matrix by None frequency
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Java Program to sort a subset of array elements
- Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
- Implementing insertion sort to sort array of numbers in increasing order using JavaScript
