Python | Delete elements with frequency atmost K
Last Updated :
05 Apr, 2023
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 those elements which occur less than K times.
Method #1: Using list comprehension + count() The idea applied here is to construct a new list using list comprehension and insert only those elements which occur more than K times. The count operation is done with the help of the count function.
Python3
# Python3 code to demonstrate
# remove elements less than and equal K
# using list comprehension + count()
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 2
# using list comprehension + count()
# remove elements less than K
res = [ i for i in test_list if test_list.count(i) > K]
# print result
print("The list removing elements less than and equal K : " + str(res))
Output : The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K : [3, 2, 3, 3, 2, 2, 2]
Time complexity: O(n^2), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Method #2: Using Counter() + list comprehension This problem can be efficiently solved using the Counter function that precomputes the count of each element in list so that the decision to keep or reject a particular element takes lesser time.
Python3
# Python3 code to demonstrate
# remove elements less than and equal K
# using Counter() + list comprehension
from collections import Counter
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 2
# using Counter() + list comprehension
# remove elements less than K
freq = Counter(test_list)
res = [ele for ele in test_list if freq[ele] > K]
# print result
print("The list removing elements less than and equal K : " + str(res))
Output : The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K : [3, 2, 3, 3, 2, 2, 2]
Method #3: Using operator.countOf() method
Python3
import operator as op
# Python3 code to demonstrate
# remove elements less than and equal K
# using list comprehension + operator.countOf()
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 2
# using list comprehension + operator.countOf()
# remove elements less than K
res = [i for i in test_list if op.countOf(test_list, i) > K]
# print result
print("The list removing elements less than and equal K : " + str(res))
OutputThe original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K : [3, 2, 3, 3, 2, 2, 2]
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #4: Using numpy:
Algorithm:
- Initialize the input list and the threshold K.
- Use the reduce function from the functools module to count the frequency of each element in the list.
- Create a NumPy array from the input list.
- Create a boolean mask for the elements with frequency greater than K.
- Filter the elements from the NumPy array using the boolean mask.
- Convert the resulting NumPy array to a list using the tolist() method.
- Print the final list as the output.
Python3
from functools import reduce
import numpy as np
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
K = 2
# printing original list
print("The original list : " + str(test_list))
# count the frequency of each element in the list
freq = reduce(lambda d, x: {**d, x: d.get(x, 0) + 1}, test_list, {})
# create a NumPy array from the list
arr = np.array(test_list)
# create a boolean mask for the elements with frequency > K
mask = np.array([freq[x] > K for x in arr])
# use the boolean mask to filter the elements
res = arr[mask]
print("The list removing elements less than and equal K : " +str(res.tolist()))
#This code is contributed by Rayudu
Output:
The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K : [3, 2, 3, 3, 2, 2, 2]
Time complexity:
The time complexity of this code is O(n), where n is the length of the input list. The reduce function takes O(n) time to count the frequency of each element in the list, and the creation of the boolean mask and filtering of the elements takes O(n) time as well. The conversion of the NumPy array to a list takes O(n) time
Auxiliary Space:
The space complexity of this code is O(n), where n is the length of the input list. The frequency dictionary created using the reduce function can take up to O(n) space in the worst case if all the elements in the list are unique. The NumPy array created from the list also takes O(n) space. The boolean mask and the filtered array take up additional O(n) space. Therefore, the overall space complexity is O(n).
Method #5: Using the heapq method:
Algorithm:
- Initialize an empty heap.
- Traverse through the input list and count the frequency of each element and check if the count of an element is greater than K. If yes, then add that element to the heap.
- After traversing the whole list, the heap will contain all elements with a frequency greater than K.
- Finally, extract all elements from the heap and add them to the result list.
- The resulting list will contain all elements with a frequency greater than K.
Below is the implementation of the above approach:
Python3
import heapq
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 2
# using heapq method remove elements
# less than K
res = [i for i in test_list if test_list.count(i) > K]
heapq.heapify(res)
# print result
print("The list removing elements less than and equal K : " + str(res))
# This code is contributed by Jyothi pinjala.
OutputThe original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K : [2, 2, 2, 3, 2, 3, 3]
Time Complexity: The time complexity of this approach is O(n*log k), where n is the length of the input list and k is the size of the heap. The time complexity of counting the frequency of each element is O(n). The time complexity of adding an element to the heap is O(log K). Since we add each element to the heap only if its frequency is greater than K, the maximum size of the heap will be the number of unique elements with a frequency greater than K.
Space Complexity: The space complexity of this approach is O(k), where k is the maximum size of the heap. We need to store at most k elements in the heap.
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 - Similar Consecutive elements frequency
Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop
5 min read
Python | Tuple Column element frequency
In Python, we need to handle various forms of data and one among them is a list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the Kth element in the list of tuples. Letâs discuss certain ways in which this can
5 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
Python - Extract elements with equal frequency as value
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 :
6 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 - Consecutive elements maximum frequencies
Sometimes, while working with Python lists we can have a problem in which we need to extract the maximum frequencies of consecutive elements. This kind of problem can occur as application in many domains such as day-day programming and competitive programming. Let's discuss certain ways in which thi
5 min read
Python - Accessing K element in set without deletion
In this article given a set(), the task is to write a Python program to access an element K, without performing deletion using pop(). Example: Input : test_set = {6, 4, 2, 7, 9}, K = 7 Output : 3 Explanation : 7 occurs in 3rd index in set. Input : test_set = {6, 4, 2, 7, 9}, K = 9 Output : 4 Explana
4 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