Teaching Kids Programming: Videos on Data Structures and Algorithms
A Mode in Math is the most frequent number in an array. If there are multiple elements that appear equally the same time, then the mode can be one of them (or the first appearing one).
Finding the Mode in Python
First of all, we need to iterate the numbers in the list and count how many for each of them, we can use a hash map (i.e. dictionary):
1 2 3 4 5 6 | d = {} for i in nums: if i in d: d[i] += 1 else: d[i] = 1 |
d = {} for i in nums: if i in d: d[i] += 1 else: d[i] = 1
{} is the most simplest dictionary declaration which is the same as “dict()”. However, with this, if a key is not existent in the dictionary, an error will be raised thus we need to check if a number appears first time then assign to one. We can however, use defaultdict class from collections which applies a default value when a key is not existent.
1 2 3 4 | from collections import defaultdict for i in nums: d[i] += 1 |
from collections import defaultdict for i in nums: d[i] += 1
We can use the Counter from collections to do exactly the counting:
1 2 3 | from collections import Counter d = Counter(nums) |
from collections import Counter d = Counter(nums)
And then, we can find the most appearing frequency value.
1 | n = max(d.Values()) |
n = max(d.Values())
And then we iterate again the numbers and return the first one that has the most frequency:
1 2 3 4 5 6 7 8 | def mode(nums): if not nums: return None d = Counter(nums) n = max(d.values()) for i in nums: if d[i] == n: return i |
def mode(nums): if not nums: return None d = Counter(nums) n = max(d.values()) for i in nums: if d[i] == n: return i
We can use the max(d, key=d.get) to return the key which has the largest value. Thus, the simple Python Function to compute the Mode for a Array/List is:
1 2 3 | def mode(nums): c = Counter(nums) return max(c, key=c.get) |
def mode(nums): c = Counter(nums) return max(c, key=c.get)
Time complexity is O(N) i.e. iterating the number twice and space complexity is O(N) as we need a hash table aka dictionary.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Teaching Kids Programming - Compute the Number of Sublists by Combination in Math
Next Post: Teaching Kids Programming - Repeated K-Length Substrings (Sliding Window)