how to get mode of a list in python characters code example
Example 1: calculate mode in python
from collections import Counter
def calculate_mode(n):
c = Counter(n)
num_freq = c.most_common()
max_count = num_freq[0][1]
modes = []
for num in num_freq:
if num[1] == max_count:
modes.append(num[0])
return modes
def calculate_mode(n):
c = Counter(n)
mode = c.most_common(1)
return mode[0][0]
Example 2: python finding mode of a list
import random
numbers = []
limit = int(input("Please enter how many numbers you would like to compare:\n"))
mode =0
for i in range(0,limit):
numbers.append(random.randint(1,10))
maxiumNum = max(numbers)
j = maxiumNum + 1
count = [0]*j
for i in range(j):
count[i]=0
for i in range(limit):
count[numbers[i]] +=1
n = count[0]
for i in range(1, j):
if (count[i] > n):
n = count[i]
mode = i
print("This is the mode = "+str(mode))
print("This is the array = "+str(numbers))