+

Python program to check if a given value occurs at least k times

We can use lists to solve this problem. We can add each occurrence of a given value and check if it is greater than or equal to k. If the return value — True then set the flag to 1, otherwise 0.

Below is the Python implementation —

# Python program to check if given
# the value occurs at least k times

 

test_list = [ 1 , 3 , 5 , 5 , 4 , 5

 
# print original list

print ( "The original list is:" + str (test_list)) 

 
# value to check

val = 5

  
# initialize to

k = 3

 
# using sum () + list comprehension
# checking occurrences

res = 0

res = sum ([ 1 for i in test_list if i = = val]) & gt; = k

 

if res = = 1 : res = True

else : res = False

 
# print result

print ( "% d occur atleast% d times? : " % (val, k) + str (res)) 

Exit:

 The original list is: [1, 3, 5, 5, 4, 5] 5 occur atleast 3 times?: True                                        
             
                
Get Solution for free from DataCamp guru