You have a list of N integers and you need to determine the K most frequent integers. Which of the following Python data
structures should you use to do this in the most efficient way?
Answers
Answered by
4
def most_freq(l, k):
f = {n: l.count(n) for n in l}
sorted_f = dict(sorted(f.items(), key = lambda x: x[1], reverse = True))
return dict(list(sorted_f.items())[0:k])
l, k = [14, 12, 15, 17, 4, 9, 16, 11, 1, 3, 9, 16, 3, 12, 1,
12, 4, 10, 17, 1], 3
print(most_freq(l, k))
Similar questions