Doing more data structure work; asked to find if an array of numbers has a majority element – that is, an element that appears more than 50% of the time in the array.
My assignment is to write a greedy algorithm to do this…but wouldn't it be easier to just use the
from collections import Counter def majority_element_finder(numbers): return Counter(numbers).most_common() > (len(numbers) // 2)
most_common([n]) returns a list of tuples of the elements in
numbers along with the number of times each appears. This is listed in decreasing order. We want to take the first element's (
) count (''), and see if it's greater than half the length of the list.