Created
May 17, 2018 02:20
-
-
Save gabraganca/04f0d2cb8c2976072f0b0b3264588507 to your computer and use it in GitHub Desktop.
Get the most frequent number from a list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def MostPopularNumber(array, array_length=None): | |
""" | |
Get the most frequent number from an array. | |
If there arre two or more numbers that appear | |
the same number of times, return the lowest. | |
Parameters | |
---------- | |
array: list | |
Array of numbers | |
array_length: int (deprecated) | |
size of array | |
Returns | |
------- | |
Most frequent number. | |
""" | |
from collections import Counter | |
# Check if all number of the lista re less than 5000 | |
for i in array: | |
if i <1 or i>5000: | |
raise ValueError('Numbers should be between 1 and 5000') | |
c = Counter(array) | |
hi_freq = c.most_common()[0][1] | |
most_common = [number | |
for number, count in c.most_common() | |
if count == hi_freq] | |
return min(most_common) | |
assert MostPopularNumber([34,31,34,77,82], 5) == 34 | |
assert MostPopularNumber([22, 101, 102, 101, 102, 525, 88], 7) == 101 | |
assert MostPopularNumber([66], 1) == 66 | |
assert MostPopularNumber([14, 14, 2342, 2342, 2342], 5) == 2342 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment