Created
October 19, 2018 02:42
-
-
Save akey7/c128c2dfb83ea9b7e66d6c527240d4f9 to your computer and use it in GitHub Desktop.
Mode finding's in Python lists
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 mode(xs): | |
""" | |
This returns the mode of the values in xs. xs is a standard | |
Python list with discrete values, which can be of any hashable | |
value. | |
Fo this problem, think about using a dictionary in some way. | |
What could be the keys? The values? Also remember that dictionaries | |
are UNORDERED--in other words, there is no guaranteed order. | |
Parameters | |
---------- | |
xs: Values for which to find the mode. | |
Returns | |
------- | |
There are a few possibilities: | |
1. Empty list: Return None | |
2. One element in list: Return that element | |
3. There are ties in the counts of the items: Return ANY tied item. | |
4. There is an item with a clear maximum count: Return that iem. | |
""" | |
if len(xs) == 0: | |
return None | |
elif len(xs) == 1: | |
return xs[0] | |
else: | |
counts = {} | |
for x in xs: | |
if x in counts: | |
counts[x] += 1 | |
else: | |
counts[x] = 1 | |
maxCount = 0 | |
maxKey = None | |
for key, count in counts.items(): | |
if count >= maxCount: | |
maxCount = count | |
maxKey = key | |
return maxKey | |
if __name__ == '__main__': | |
print(mode([])) | |
print(mode(['alpha'])) | |
print(mode(['bravo', 'alpha'])) | |
print(mode(['bravo', 'bravo', 'alpha', 'charlie', 'charlie', 'charlie'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment