Python - Extract elements with equal frequency as value
Last Updated :
27 Mar, 2023
Given a list, extract all the elements having same frequency as its value.
Examples:
Input : test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Output : [1, 3, 4]
Explanation : All elements occur equal times as their value.
Input : test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4]
Output : [1, 3]
Explanation : All elements occur equal times as their value.
Method #1 : Using list comprehension + count()
In this, task of getting frequency is done using count(), list comprehension is used to iterate for each element, compare and extract.
Python3
# Python3 code to demonstrate working of
# Extract elements with equal frequency as value
# Using list comprehension + count()
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
# printing original list
print("The original list is : " + str(test_list))
# removing duplicates using set()
# count() for computing frequency
res = list(set([ele for ele in test_list if test_list.count(ele) == ele]))
# printing result
print("Filtered elements : " + str(res))
OutputThe original list is : [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Filtered elements : [1, 3, 4]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using filter() + lambda + count()
In this, we perform task of filtering elements using filter() and lambda, count() again is used to get count of all the elements.
Python3
# Python3 code to demonstrate working of
# Extract elements with equal frequency as value
# Using filter() + lambda + count()
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
# printing original list
print("The original list is : " + str(test_list))
# removing duplicates using set()
# count() for computing frequency
# filter used to perform filtering
res = list(set(list(filter(lambda ele : test_list.count(ele) == ele, test_list))))
# printing result
print("Filtered elements : " + str(res))
OutputThe original list is : [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Filtered elements : [1, 3, 4]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. This is because we’re using the built-in filter() + lambda + count() which all has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), no extra space is required
Method #3 : Using Counter() + items() + sort()
Python3
# Python3 code to demonstrate working of
# Extract elements with equal frequency as value
from collections import Counter
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
# printing original list
print("The original list is : " + str(test_list))
freq = Counter(test_list)
res = []
for key, value in freq.items():
if(key == value):
res.append(key)
res.sort()
# printing result
print("Filtered elements : " + str(res))
Output
The original list is : [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Filtered elements : [1, 3, 4]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using list comprehension + operator.countOf()
In this, task of getting frequency is done using operator.countOf(), list comprehension is used to iterate for each element, compare and extract.
Python3
# Python3 code to demonstrate working of
# Extract elements with equal frequency as value
# Using list comprehension + operator.countOf()
import operator as op
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
# printing original list
print("The original list is : " + str(test_list))
# removing duplicates using set()
# operator.countOf() for computing frequency
res = list(set([ele for ele in test_list if op.countOf(test_list,ele) == ele]))
# printing result
print("Filtered elements : " + str(res))
OutputThe original list is : [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Filtered elements : [1, 3, 4]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using numpy module
Algorithm:
- Initialize the input list.
- Print the original list.
- Create a new list by iterating over the input list using a list comprehension.
- For each element in the input list, check if its frequency is equal to its value using the count() method.
- If the frequency is equal to the value, add the element to the new list.
- Remove duplicates from the new list using the set() method.
- Convert the set back to a list and store it in the variable "res".
- Print the filtered elements.
Python3
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
# printing original list
print("The original list is : " + str(test_list))
# removing duplicates using set()
# count() for computing frequency
# list comprehension to filter out elements with equal frequency as value
res = list(set([ele for ele in test_list if test_list.count(ele) == ele]))
# printing result
print("Filtered elements : " + str(res))
# This code is contributed by Jyothi pinjala
OutputThe original list is : [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Filtered elements : [1, 3, 4]
Time complexity: O(n^2) (due to the use of count() method within the list comprehension)
Auxiliary Space: O(n) (due to the creation of a new list to store the filtered elements)
Method #6: Using recursion
Algorithm:
- Define a recursive function count_freq that takes a list test_list, an element ele and an integer count as input.
- The function returns the frequency of the element ele in the list test_list.
- If the input test_list is empty, the function returns the value of count.
- If the first element of test_list is equal to ele, increment count by 1.
- Recursively call the count_freq function with the remainder of test_list and the same ele and count.
- Define a function filter_elements that takes a list test_list as input.
- Initialize an empty list res.
- Iterate over the set of unique elements in test_list.
- If the frequency of the current element in test_list is equal to the value of the element, append the element to res.
- Return res.
Python3
def count_freq(test_list, ele, count=0):
if not test_list:
return count
if test_list[0] == ele:
count += 1
return count_freq(test_list[1:], ele, count)
def filter_elements(test_list):
res = []
for ele in set(test_list):
if count_freq(test_list, ele) == ele:
res.append(ele)
return res
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
print("The original list is : " + str(test_list))
filtered_list = filter_elements(test_list)
print("Filtered elements : " + str(filtered_list))
#This code is contributed by Rayudu
OutputThe original list is : [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Filtered elements : [1, 3, 4]
Time complexity: O(n)
Where n is the length of the input test_list. The filter_elements function iterates over the set of unique elements in test_list, and for each element, calls the count_freq function, which has a time complexity of O(n). Therefore, the time complexity of the entire algorithm is O(n^2).
Auxiliary Space: O(n)
Due to the recursive calls on the stack. The filter_elements function stores a list of unique elements in test_list, which has a space complexity of O(n) and creates a list res to store the filtered elements, which has a space complexity of O(m) where m is the number of filtered elements. Therefore, the overall space complexity of the algorithm is O(n + m).
Similar Reads
Python | Elements with Frequency equal K
This is one of the most essential operation that programmer quite often comes in terms with. Be it development or competitive programming, this utility is quite essential to master as it helps to perform many tasks that involve this task to be its subtask. Lets discuss approach to achieve this opera
3 min read
Python - Extract elements with Frequency greater than K
Given a List, extract all elements whose frequency is greater than K. Input : test_list = [4, 6, 4, 3, 3, 4, 3, 4, 3, 8], K = 3 Output : [4, 3] Explanation : Both elements occur 4 times. Input : test_list = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6], K = 2 Output : [4, 3, 6] Explanation : Occur 4, 3, and 3 time
7 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 Program to Extract Rows of a matrix with Even frequency Elements
Given a Matrix, the task is to write a Python program to extract all the rows which have even frequencies of elements. Examples: Input: [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2], [6, 5, 6, 5], [1, 2, 3, 4]] Output: [[4, 4, 4, 4, 2, 2], [6, 5, 6, 5]]Explanation: frequency of 4-> 4 which is even frequency
5 min read
Python | Delete elements with frequency atmost K
Many methods can be employed to perform the deletion in the list. Be it the remove function, pop function, and many other functions. But most of the time, we usually don't deal with the simple deletion, but with certain constraints. This article discusses certain ways in which we can delete only tho
7 min read
Python - Extract elements with Range consecutive occurrences
Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur range times consecutively. This problem can occur in many domains. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using groupby() + list comprehension This
4 min read
Python - False values Frequency
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization like in data Science. Lets discuss certain ways
5 min read
Extract Elements from list in set - Python
We are given a list and our task is to extract unique elements from list in a set. For example: a = [1, 2, 3, 4, 5, 2, 3, 6] here we would only extract those elements from list which are unique hence resultant output would be {1,2,3,4,5,6}.Using Set Conversion In this method we convert the list into
2 min read
Python - Keys Values equal frequency
Given a dictionary, count instances where keys are equal to values. Input : test_dict = {5:5, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 2 Explanation : At 2 instances, keys are equal to values.Input : test_dict = {5:4, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 1 Explanation : At 1 instance, key is equal to valu
4 min read
Python - Elements frequency in Tuple
Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using def
7 min read