Top K Frequent elements

Run Settings
LanguagePython
Language Version
Run Command
class Solution: def top_frequent_elements(self, array, k_elements): frequency = {} for num in array: if num not in frequency: frequency[num] = 1 else: frequency[num] += 1 return_value = [] for k in range(k_elements): max_count = 1 most_frequent_num = next(iter(frequency)) for key,value in frequency.items(): if value > max_count: max_count = value most_frequent_num = key return_value.append(most_frequent_num) del(frequency[most_frequent_num]) return return_value print("Hello World!") sample1 = [2,1,1,3,1,2] k1 = 2 sol = Solution() result1 = sol.top_frequent_elements(sample1, k1) print(result1) assert(result1 == [1,2]) sample2 = [1] k2 = 1 sol = Solution() result2 = sol.top_frequent_elements(sample2, k2) print(result2) assert(result2 == [1]) print("Good bye cruel World")
Editor Settings
Theme
Key bindings
Full width
Lines