Python – Fractional Frequency of elements in List
Last Updated :
05 Apr, 2023
Given a List, get fractional frequency of each element at each position.
Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4]
Output : [‘1/4’, ‘1/3’, ‘2/4’, ‘1/1’, ‘1/1’, ‘2/3’, ‘3/4’, ‘3/3’, ‘4/4’]
Explanation : 4 occurs 1/4th of total occurrences till 1st index, and so on.
Input : test_list = [4, 5, 4, 6, 7, 5]
Output : [‘1/2’, ‘1/2’, ‘2/2’, ‘1/1’, ‘1/1’, ‘2/2’]
Explanation : 4 occurs 1/2th of total occurrences till 1st index, and so on.
Method : Using Counter() + loop + dictionary comprehension
In this, we use Counter() to get the frequency of each element in list and to form denominator part of fraction. Numerator is initialized to 0 for each element. Then loop is used to add the elements in numerator and join with total frequency in denominator.
Python3
from collections import Counter
test_list = [ 4 , 5 , 4 , 6 , 7 , 5 , 4 , 5 , 4 , 6 , 4 , 6 ]
print ( "The original list is : " + str (test_list))
number = {idx : 0 for idx in set (test_list)}
denom = Counter(test_list)
res = []
for ele in test_list:
number[ele] + = 1
res.append( str (number[ele]) + '/' + str (denom[ele]))
print ( "Fractional Frequency List : " + str (res))
|
Output
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6]
Fractional Frequency List : ['1/5', '1/3', '2/5', '1/3', '1/1', '2/3', '3/5', '3/3', '4/5', '2/3', '5/5', '3/3']
Time Complexity: O(n*n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method : Using list(),set(),count() methods
Approach
- Create a dictionary with unique values of list as keys and values as their occurences in original list (using list(),set(),count()) methods
- Initiate a for loop to traverse the original list to append the fractional frequency of output list(using count())
- Display output list
Python3
test_list = [ 4 , 5 , 4 , 6 , 7 , 5 , 4 , 5 , 4 , 6 , 4 , 6 ]
print ( "The original list is : " + str (test_list))
x = list ( set (test_list))
d = dict ()
for i in x:
d[i] = test_list.count(i)
res = []
for i in range ( 0 , len (test_list)):
a = test_list[:i + 1 ].count(test_list[i])
res.append( str (a) + "/" + str (d[test_list[i]]))
print ( "Fractional Frequency List : " + str (res))
|
Output
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6]
Fractional Frequency List : ['1/5', '1/3', '2/5', '1/3', '1/1', '2/3', '3/5', '3/3', '4/5', '2/3', '5/5', '3/3']
Time Complexity: O(n*n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method : Using numpy:
Algorithm:
- Initialize an empty list “freq_list”.
- Find the unique values and their respective counts in the given list “test_list” using numpy’s unique() method.
- For each unique value, get the indices where the value occurs in “test_list” using numpy’s where() method.
- For each index of the unique value, calculate the fractional frequency by dividing the count of the value by the number of times it occurs in the sublist from the start of “test_list” up to the current index.
- Append the fractional frequency to the “freq_list”.
- Print the “freq_list”.
Python3
import numpy as np
test_list = [ 4 , 5 , 4 , 6 , 7 , 5 , 4 , 5 , 4 , 6 , 4 , 6 ]
print ( "The original list is : " + str (test_list))
unique_vals, counts = np.unique(test_list, return_counts = True )
freq_list = []
for val, count in zip (unique_vals, counts):
indices = np.where(test_list = = val)[ 0 ]
for i in range ( len (indices)):
freq_list.append(
"{}/{}" . format (np.count_nonzero(test_list[:indices[i] + 1 ] = = val), count))
print ( "Fractional Frequency List : " + str (freq_list))
|
Output:
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6]
Fractional Frequency List : ['1/5', '2/5', '3/5', '4/5', '5/5', '1/3', '2/3', '3/3', '1/3', '2/3', '3/3', '1/1']
Time Complexity: O(n^2), where n is the length of the input list. The worst-case scenario occurs when all the elements of the list are unique and the nested loop runs n times for each element.
Space Complexity: O(n), where n is the length of the input list. The space required by the “freq_list” increases linearly with the length of the input list.
Method : Using list(), set(), operator.countOf() methods:
Approach:
- Create a dictionary with unique values of the list as keys and values as their occurrences in the original list (using list(),set(),operator.countOf()) methods.
- Initiate a for loop to traverse the original list to append the fractional frequency of output list(using operator.countOf()).
- Display the output list.
Below is the implementation of the above approach:
Python3
import operator
test_list = [ 4 , 5 , 4 , 6 , 7 , 5 , 4 , 5 , 4 , 6 , 4 , 6 ]
print ( "The original list is : " + str (test_list))
x = list ( set (test_list))
d = dict ()
for i in x:
d[i] = operator.countOf(test_list, i)
res = []
for i in range ( 0 , len (test_list)):
a = operator.countOf(test_list[:i + 1 ], test_list[i])
res.append( str (a) + "/" + str (d[test_list[i]]))
print ( "Fractional Frequency List : " + str (res))
|
Output
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6]
Fractional Frequency List : ['1/5', '1/3', '2/5', '1/3', '1/1', '2/3', '3/5', '3/3', '4/5', '2/3', '5/5', '3/3']
Time Complexity: O(n*n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Similar Reads
Python - List Frequency of Elements
We are given a list we need to count frequencies of all elements in given list. For example, n = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to count frequencies so that output should be {4: 4, 3: 3, 2: 2, 1: 1}. Using collections.Countercollections.Counter class provides a dictionary-like structure that
2 min read
Python - Step Frequency of elements in List
Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
4 min read
Python | Frequency grouping of list elements
Sometimes, while working with lists, we can have a problem in which we need to group element along with it's frequency in form of list of tuple. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute force method to perform this particular task. In this
6 min read
Python | Find most frequent element in a list
Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python. Example Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we
2 min read
Python | Extract least frequency element
Sometimes, while working with data, we can have a problem in which we need to extract element which is occurring least number of times in the list. Let's discuss certain ways in which this problem can be solved. Method #1: Using defaultdict() + loop The combination of above functions can be used to
5 min read
Python | Find sum of frequency of given elements in the list
Given two lists containing integers, the task is to find the sum of the frequency of elements of the first list in the second list. Example: Input: list1 = [1, 2, 3] list2 = [2, 1, 2, 1, 3, 5, 2, 3] Output: 7 Explanation: No of time 1 occurring in list2 is :2 No of time 2 occurring in list2 is :3 No
4 min read
Frequency of Elements from Other List - Python
We are given a list of elements and another list containing specific values and our task is to count the occurrences of these specific values in the first list "a" and return their frequencies. For example: a = [1, 2, 2, 3, 4, 2, 5, 3, 1], b = [1, 2, 3]. Here b contains the elements whose frequency
3 min read
Python - Restrict Elements Frequency in List
Given a List, and elements frequency list, restrict frequency of elements in list from frequency list. Input : test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6], restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 1} Output : [1, 4, 5, 4, 4, 6] Explanation : Limit of 1 is 1, any occurrence more than that is removed.
5 min read
Python | Group list elements based on frequency
Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple. Examples: Input : [1, 3, 4, 4, 1, 5, 3, 1] Output : [(1, 3), (3, 2), (4, 2), (5, 1)] Input : ['x', 'a', 'x', 'y', 'a', 'x'] Output : [('x', 3), ('a', 2), ('y', 1)] Method #1: List c
5 min read
Python - Elements frequency count in multiple lists
Sometimes while working with Python lists we can have a problem in which we need to extract the frequency of elements in list. But this can be added work if we have more than 1 list we work on. Let's discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension
6 min read