Python - Restrict Elements Frequency in List
Last Updated :
08 May, 2023
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. Similar with all elements.
Input : test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6], restrct_dict = {4 : 2, 1 : 1, 6 : 1, 5 : 1}
Output : [1, 4, 5, 4, 6]
Explanation : Limit of 4 is 3, any occurrence more than that is removed. Similar with all elements.
Method 1 : Using loop + defaultdict()
In this, we iterate for elements and and maintain lookup counter for each element using defaultdict(), if any element exceeds restrict dict, that element is not added then onwards.
Python3
# Python3 code to demonstrate working of
# Restrict Elements Frequency in List
# Using loop + defaultdict()
from collections import defaultdict
# initializing list
test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
# printing original list
print("The original list is : " + str(test_list))
# initializing restrct_dict
restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 2}
res = []
lookp = defaultdict(int)
for ele in test_list:
lookp[ele] += 1
# move to next ele if greater than restrct_dict count
if lookp[ele] > restrct_dict[ele]:
continue
else:
res.append(ele)
# printing results
print("Filtered List : " + str(res))
OutputThe original list is : [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
Filtered List : [1, 4, 5, 4, 4, 5, 6]
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the new res list
Method #2: Using reduce():
Algorithm :
- Create an input list 'test_list' with the given elements.
- Create a dictionary 'restrct_dict' with the restriction values for each element.
- Initialize an empty dictionary 'lookp' to keep track of the frequency of each element in 'test_list'.
- Define a function 'filter_list' that takes an accumulator, an element of 'test_list', and applies the restriction to that element based on the 'restrct_dict' and updates the accumulator with the element if it meets the restriction.
- Use the reduce() function from functools module to apply the 'filter_list' function to each element of the 'test_list' and get a filtered list.
- Print the filtered list.
Python3
from collections import defaultdict
from functools import reduce
# initializing list
test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
# initializing restrct_dict
restrct_dict = {4: 3, 1: 1, 6: 1, 5: 2}
# printing original list
print("The original list is : " + str(test_list))
lookp = defaultdict(int)
# function to filter the list based on restriction dictionary
def filter_list(acc, ele):
lookp[ele] += 1
if lookp[ele] <= restrct_dict.get(ele, float('inf')):
return acc + [ele]
return acc
# using reduce() to apply filter_list on each element of test_list
res = reduce(filter_list, test_list, [])
# printing results
print("Filtered List : " + str(res))
#This code is contrinuted by Pushpa.
OutputThe original list is : [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
Filtered List : [1, 4, 5, 4, 4, 5, 6]
Time Complexity: O(n), where n is the length of the input list 'test_list'. This is because we are iterating through each element in the list once to apply the filter.
Auxiliary Space: O(m), where m is the number of distinct elements in the input list 'test_list'. This is because we are using a dictionary to keep track of the frequency of each element in the list. The space required by the dictionary is proportional to the number of distinct elements in the list.
Method #3 : Using count() method
Approach
- Initiate a for loop from i = 0 to len(test_list)
- Slice test_list from beginning to i index and check whether the count of test_list[i] is less than the value of key test_list[i] in restrct_dict (using count() method)
- If yes append test_list[i] to output list res
- Display res
Python3
# Python3 code to demonstrate working of
# Restrict Elements Frequency in List
# initializing list
test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
# printing original list
print("The original list is : " + str(test_list))
# initializing restrct_dict
restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 2}
res=[]
for i in range(0,len(test_list)):
if test_list[:i].count(test_list[i])<restrct_dict[test_list[i]]:
res.append(test_list[i])
# printing results
print("Filtered List : " + str(res))
OutputThe original list is : [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
Filtered List : [1, 4, 5, 4, 4, 5, 6]
Time Complexity : O(N) N - length of test_list
Auxiliary Space : O(N) N - length of res
Method #4 : Using operator.countOf() method
Approach
- Initiate a for loop from i = 0 to len(test_list)
- Slice test_list from the beginning to i index and check whether the count of test_list[i] is less than the value of key test_list[i] in restrct_dict (using operator.countOf() method)
- If yes append test_list[i] to output list res
- Display res
Python3
# Python3 code to demonstrate working of
# Restrict Elements Frequency in List
# initializing list
test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
# printing original list
print("The original list is : " + str(test_list))
# initializing restrct_dict
restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 2}
res=[]
import operator
for i in range(0,len(test_list)):
if operator.countOf(test_list[:i],test_list[i])<restrct_dict[test_list[i]]:
res.append(test_list[i])
# printing results
print("Filtered List : " + str(res))
OutputThe original list is : [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
Filtered List : [1, 4, 5, 4, 4, 5, 6]
Time Complexity : O(N) N - length of test_list
Auxiliary Space : O(N) N - length of res
Similar Reads
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
Sort List Elements by Frequency - Python Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
3 min read
Sort List Elements by Frequency - Python Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
3 min read
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 - 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 | 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