1# Calculating the mode when the list of numbers may have multiple modes
2from collections import Counter
3
4def calculate_mode(n):
5 c = Counter(n)
6 num_freq = c.most_common()
7 max_count = num_freq[0][1]
8
9 modes = []
10 for num in num_freq:
11 if num[1] == max_count:
12 modes.append(num[0])
13 return modes
14
15# Finding the Mode
16
17def calculate_mode(n):
18 c = Counter(n)
19 mode = c.most_common(1)
20 return mode[0][0]
21
22#src : Doing Math With Python.
1import random
2numbers = []
3limit = int(input("Please enter how many numbers you would like to compare:\n"))
4mode =0
5for i in range(0,limit):
6 numbers.append(random.randint(1,10))
7
8maxiumNum = max(numbers)
9j = maxiumNum + 1
10count = [0]*j
11for i in range(j):
12 count[i]=0
13
14for i in range(limit):
15 count[numbers[i]] +=1
16
17n = count[0]
18for i in range(1, j):
19 if (count[i] > n):
20 n = count[i]
21 mode = i
22
23print("This is the mode = "+str(mode))
24print("This is the array = "+str(numbers))
25
26
1from scipy import stats
2speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
3x = stats.mode(speed)
4print(x)
1>>> from collections import Counter
2
3>>> def my_mode(sample):
4... c = Counter(sample)
5... return [k for k, v in c.items() if v == c.most_common(1)[0][1]]
6...
7
8>>> my_mode(["male", "male", "female", "male"])
9['male']
10
11>>> my_mode(["few", "few", "many", "some", "many"])
12['few', 'many']
13
14>>> my_mode([4, 1, 2, 2, 3, 5])
15[2]
16
17>>> my_mode([4, 1, 2, 2, 3, 5, 4])
18[4, 2]
19