Python | Check if any element occurs n times in given list
Last Updated :
08 May, 2023
Given a list, the task is to find whether any element occurs 'n' times in given list of integers. It will basically check for the first element that occurs n number of times.
Examples:
Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3
Output : 2
Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4
Output : 1
Below are some methods to do the task in Python -
Method 1: Using Simple Iteration and Sort
Python3
# Python code to find occurrence of any element
# appearing 'n' times
# Input Initialisation
input = [1, 2, 3, 0, 4, 3, 4, 0, 0]
# Sort Input
input.sort()
# Constants Declaration
n = 3
prev = -1
count = 0
flag = 0
# Iterating
for item in input:
if item == prev:
count = count + 1
else:
count = 1
prev = item
if count == n:
flag = 1
print("There are {} occurrences of {} in {}".format(n, item, input))
break
# If no element is not found.
if flag == 0:
print("No occurrences found")
OutputThere are 3 occurrences of 0 in [0, 0, 0, 1, 2, 3, 3, 4, 4]
Time complexity: O(n*logn), as sort() function is used.
Auxiliary space: O(1)
Method 2: Using Count
Python3
# Python code to find occurrence of any element
# appearing 'n' times
# Input list initialisation
input = [1, 2, 3, 4, 0, 4, 3, 4]
# Constant declaration
n = 3
# print
print("There are {} occurrences of {} in {}".format(input.count(n), n, input))
OutputThere are 2 occurrences of 3 in [1, 2, 3, 4, 0, 4, 3, 4]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), as only a constant amount of extra space is used.
Method 3: Using defaultdict
We first populate item of list in a dictionary and then we find whether count of any element is equal to n.
Python3
# Python code to find occurrence of any element
# appearing 'n' times
# importing
from collections import defaultdict
# Dictionary declaration
dic = defaultdict(int)
# Input list initialisation
Input = [9, 8, 7, 6, 5, 9, 2]
# Dictionary populate
for i in Input:
dic[i]+= 1
# constant declaration
n = 2
flag = 0
# Finding from dictionary
for element in Input:
if element in dic.keys() and dic[element] == n:
print("Yes, {} has {} occurrence in {}.".format(element, n, Input))
flag = 1
break
# if element not found.
if flag == 0:
print("No occurrences found")
OutputYes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2].
Method #4 : Using Counter() function
Python3
# Python code to find occurrence of any element
# appearing 'n' times
# importing
from collections import Counter
# Input list initialisation
Input = [9, 8, 7, 6, 5, 9, 2]
freq = Counter(Input)
# constant declaration
n = 2
if n in freq.values():
for key, value in freq.items():
if(value == n):
print("Yes, {} has {} occurrence in {}.".format(key, n, Input))
# if element not found.
else:
print("No occurrences found")
OutputYes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2].
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#5:Using regular expressions
Python3
import re
# Input list initialisation
input_list = [9, 8, 7, 6, 5, 9, 2]
# constant declaration
n = 2
occurrences = {}
for item in input_list:
occurrences[item] = occurrences.get(item, 0) + 1
result = [item for item, count in occurrences.items() if count == n]
if result:
print("Yes, {} has {} occurrence in {}.".format(result[0], n, input_list))
else:
print("No items appear {} times in the input list".format(n))
#This code is contributed by Vinay Pinjala.
OutputYes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2].
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#6: Using Recursive method.
Python3
def count_occurrences(input_list, item, n):
if not input_list:
return False
if input_list[0] == item:
n -= 1
if n == 0:
return True
return count_occurrences(input_list[1:], item, n)
def main():
input_list = [9, 8, 7, 6, 5, 9, 2]
n = 2
for item in set(input_list):
if count_occurrences(input_list, item, n):
print("Yes, {} has {} occurrence in {}.".format(item, n, input_list))
return
print("No items appear {} times in the input list".format(n))
if __name__ == '__main__':
main()
#this code contributed by tvsk
OutputYes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2].
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #7 : Using operator.countOf() method
Approach
- Convert the list to a unique value list using set(), and list().
- Check the unique element count in the original list is equal to N or not, If equal print("There are {} occurrences of {} in {}".format(n, i , input)), Otherwise, print("No occurrences found")
Python3
# Python code to find occurrence of any element
# appearing 'n' times
import operator
# Input list initialisation
input = [9, 8, 7, 6, 5, 9, 2]
# Constant declaration
n = 2
x = list(set(input))
res = False
for i in x:
if(operator.countOf(input, i) == n):
print("There are {} occurrences of {} in {}".format(n, i, input))
res = True
break
if(not res):
print("No occurrences found")
OutputThere are 2 occurrences of 9 in [9, 8, 7, 6, 5, 9, 2]
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Python - Check if any list element is present in Tuple Given a tuple, check if any list element is present in it. Input : test_tup = (4, 5, 10, 9, 3), check_list = [6, 7, 10, 11] Output : True Explanation : 10 occurs in both tuple and list. Input : test_tup = (4, 5, 12, 9, 3), check_list = [6, 7, 10, 11] Output : False Explanation : No common elements.
6 min read
Check if k occurs atleast n times in a list - Python We are given a list of elements, a value k and a number n. The task is to check if the value k appears at least n times in the list. For example, if the input list is [1,2 3, 1, 1, 4], k = 1 and n = 3, the output should be True because 1 appears 3 times.Using count()We can use the count() method of
3 min read
Python - Check if all elements in List are same To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. Pythona = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) OutputTrue Explanation:Converting
3 min read
Check if any element in list satisfies a condition-Python The task of checking if any element in a list satisfies a condition involves iterating through the list and returning True if at least one element meets the condition otherwise, it returns False. For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the conditio
2 min read
Python - Check if element is present in tuple We are given a tuple and our task is to find whether given element is present in tuple or not. For example x = (1, 2, 3, 4, 5) and we need to find if 3 is present in tuple so that in this case resultant output should be True.Using in Operatorin operator checks if an element is present in a tuple by
2 min read