Python Program for sorting elements of an Array by Frequency
Sorting elements of an Array by Frequency in Python
Here, in this article we will discuss the program for sorting elements of an array by frequency in python programming language. We will discuss various algorithms for sorting.
Here, we will discuss the following methods in this page.
- Method 1 : Using Collections.counter()
- Method 2 : Using Iterables.
- Method 3 : Using sorted() inbuilt function.
Let’s discuss above three methods one by one,
Method 1 :
In this method we will use Collections.counter() to count the occurrence of element present in the list.
Collections counter()
Python Counter is a container that will hold the count of each of the elements present in the container.
The counter is a sub-class available inside the dictionary class.
Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object
The counter is a sub-class available inside the dictionary class.
Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object
Method 1 : Code in Python
Run
from collections import Counter ini_list = [10, 20, 30, 40, 40, 50, 50, 50] # sorting on bais of frequency of elements result = [item for items, c in Counter(ini_list).most_common() for item in [items] * c] # printing final result print(str(result))
Output
[50, 50, 50, 40, 40, 10, 20, 30]
Method 2 :
In this method we will use iterables for sorting on the basis of frequency of elements.
Iterables in Python
Iterable is an object which can be looped over or iterated over with the help of a for loop.
Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables.
In short and simpler terms, iterable is anything that you can loop over.
Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables.
In short and simpler terms, iterable is anything that you can loop over.
Method 2 : Code in Python
Run
from collections import Counter from itertools import repeat, chain ini_list = [10, 20, 30, 40, 40, 50, 50, 50] # sorting on bais of frequency of elements result = list(chain.from_iterable(repeat(i, c) for i, c in Counter(ini_list).most_common())) # printing final result print(str(result))
Output
[50, 50, 50, 40, 40, 10, 20, 30]
Method 3 :
In this method we will use sorted() inbuilt function.
sorted() function in Python
Python sorted() function returns a sorted list from the iterable object.
Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence.
Key(optional) : A function that would server as a key or a basis of sort comparison.
Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence.
Key(optional) : A function that would server as a key or a basis of sort comparison.
Method 3 : Code in Python
Run
from collections import Counter from itertools import repeat, chain ini_list = [10, 20, 30, 40, 40, 50, 50, 50] # sorting on bais of frequency of elements result = sorted(ini_list, key = ini_list.count, reverse = True) # printing final result print(str(result))
Output
[50, 50, 50, 40, 40, 10, 20, 30]
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment
def find_element_frequency(arr):
frequency_dict = {}
for element in arr:
if element in frequency_dict:
frequency_dict[element] += 1
else:
frequency_dict[element] = 1
return frequency_dict
def custom_sort(element):
return (-frequency_dict[element], element)
# Example usage:
my_array = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
frequency_dict = find_element_frequency(my_array)
# Sort the elements by frequency
sorted_array = sorted(my_array, key=custom_sort)
print(“Sorted by frequency:”)
print(sorted_array)
arr = [10, 30, 10, 20, 10, 20, 30, 10,30]
new_lst=[]
count1=[]
count=1
for i in range(len(arr)):
if arr[i] not in new_lst:
a=arr.count(arr[i])
count1.append(a)
new_lst.append(arr[i])
print(“{} {}”.format(arr[i],a))
for i in range(len(new_lst)):
for j in range(count1[i]):
print(new_lst[i])
Join our TA Support Group on Discord, where we will help you out with all your queries.
arr= [10, 20, 30, 40, 40, 50, 50, 50]
arr.sort()
arr.reverse()
print(arr)
Hey, Join our TA Support Group on Discord, where we will help you out with all your queries: Discord
def frequency(arr,n):
visited = [False for i in range(n)];
for i in range(n):
if (visited[i] == True) :
continue
count = 1;
for j in range(i+1,n,1):
if (arr[i] == arr[j]) :
visited[j] = True
count += 1;
print(arr[i],count);
print(sorted(arr,reverse = True));
a1 = list(map(int,input().split(“,”)))
l = len(a1);
frequency(a1,l)
arr = [3, 2, 3, 1, 2, 2]
a = dict()
result = []
for i in range(len(arr)):
if arr[i] in a.keys():
a[arr[i]]+=1
else:
a[arr[i]] = 1
for i in a:
for j in range(i):
print(a[i])
def frequ(arr,n):
mp = dict()
for i in range(n):
if arr[i] in mp.keys():
mp[arr[i]]+=1
else:
mp[arr[i]]=1
for x in mp:
print(x,”:”,mp[x])
for i in range(n):
for j in range(i,n):
if mp[arr[i]]<mp[arr[j]]:
arr[i],arr[j]=arr[j],arr[i]
print(arr)
arr=[20,10,20,30,30,30,30,20,10,10,20,30,40]
n= len(arr)
frequ(arr,n)