Python | Check if any element in the given list occurs n 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 accomplish a task in Python —

Method 1: using simple iterate and sort

# Python code to find occurrences of any element
# appears & # 39; n & # 39; times

 
# Initialize input

input = [ 1 , 2 , 3 , 0 , 4 , 3 , 4 , 0 , 0 ]

 
# Sort input

input . sort ()

 
# Constant 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 the element was not found.

if flag = = 0 :

print ( "No occurrences found" )

Output:

 There are 3 occurrences of 0 in [0, 0, 0, 1, 2, 3, 3 , 4, 4] 

Method 2: using counter

# Python code to find occurrences of any element
# & # 39; n & # 39; times

 
# Initialize the input list

input = [ 1 , 2 , 3 , 4 , 0 , 4 , 3 , 4 ]

 
# Constant declaration

n = 3

  
# Print

print ( " There are {} occurrences of {} in {} " . format (n, input . count (n), input ))

Output:

 There are 3 occurrences of 2 in [1, 2, 3, 4, 0, 4, 3, 4] 

Method 3: using defaultdict

First, we fill the list item in the dictionary and then find if the number of elements is equal to any element n.

# Python code to find occurrences of any element
# appears & # 39; n & # 39; times

 
# import

from collections import defaultdict

 
# Dictionary declaration

dic = defaultdict ( int )

 
# Initialize the insertion list

Input = [ 9 , 8 , 7 , 6 , 5 , 9 , 2 ]

 
# Fill in the dictionary

for i in Input :

dic [i] + = 1

 
# permanent announcement

n = 2

flag = 0

  
# Find from dictionary

for element in Input :

if element in dic.keys () and dic [element] = = 2 :

  print ( "Yes, {} has {} occurrence in {}." . format (element, n, Input ))

flag = 1

break

 
# if the element was not found.

if flag = = 0 :

print ( "No occurrences found" )

Output:

 Yes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2]