|
| 1 | +""" |
| 2 | +Most Frequent |
| 3 | +Given an array of elements, return the element that appears most frequently. |
| 4 | +
|
| 5 | +There will always be a single most frequent element. |
| 6 | +""" |
| 7 | + |
| 8 | +import unittest |
| 9 | + |
| 10 | +class MostFrequentTest(unittest.TestCase): |
| 11 | + |
| 12 | + def test1(self): |
| 13 | + self.assertEqual(most_frequent(["a","b","a","c"]), "a") |
| 14 | + |
| 15 | + def test2(self): |
| 16 | + self.assertEqual(most_frequent([2, 3, 5, 2, 6, 3, 2, 7, 2, 9]), 2) |
| 17 | + |
| 18 | + def test3(self): |
| 19 | + self.assertEqual(most_frequent([True, False, "False", "True", False]), False) |
| 20 | + |
| 21 | + def test4(self): |
| 22 | + self.assertEqual(most_frequent([40, 20, 70, 30, 10, 40, 10, 50, 40, 60]), 40) |
| 23 | + |
| 24 | +from collections import Counter |
| 25 | +def most_frequent(arr): |
| 26 | + |
| 27 | + freq = Counter(arr) |
| 28 | + # Here we dont' need the lambda explicitly - Counter has a .get() , so you can write: |
| 29 | + # return max(freq, key=freq.get) |
| 30 | + return max(freq, key=lambda i : freq[i]) |
| 31 | + """ |
| 32 | + Guarantee: Since the problem states there will always be a single most frequent element, we don't need to handle ties. |
| 33 | + If ties were possible, we'd need extra logic. |
| 34 | + """ |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +if __name__ == "__main__": |
| 40 | + print(most_frequent(["S","u","n","n","y"])) |
| 41 | + unittest.main() |
| 42 | + |
0 commit comments