Home > Back-end >  Python program to accept a List,and extract all elements whose frequency is greater than K?
Python program to accept a List,and extract all elements whose frequency is greater than K?

Time:11-27

Python - How can I write a python program to accept a List, and extract all elements whose frequency is greater than K? Please advise?

Sample I/O:

Input List:

[4, 6, 4, 3, 3, 4, 3, 4, 6, 6]

Input K:

2

Required Output : [4, 3, 6]

CodePudding user response:

Use a list comprehension:

a = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6]
k = 2
out =  [i for i in set(a) if a.count(i) > k]

CodePudding user response:

Use counter in python

list1 = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6]
d = Counter(list1)
new_list = list([item for item in d if d[item] > 1])
print(new_list) #output: [4, 6, 3]

CodePudding user response:


inputs = 0
user_list = []

while inputs < 8:
    user_input = int(input("Enter a number: "))
    user_list.append(user_input)
    inputs  = 1

input_list = [4, 6, 4, 3, 3, 4, 6, 6]
input_k = 2

def extract(x, y):
    product = []
    for i in x:
        list_element = i
        if list_element > y:
            product.append(i)
        else:
            break
    product = list(set(product))
    return product

print(extract(user_list, input_k))
print(extract(input_list, input_k))

  • Related