Mean, Median and Mode
Given a list of integers, write a program to print the mean, median and mode.
Mean - The average value of all the numbers.
Median - The mid point value in the sorted list.
Mode - The most common value in the list. If multiple elements with same frequency are present, print all the values with same frequency in increasing order.Input
The input will be a single line containing space-separated integers.Output
For example, if the given list of integers are
2 6 3 1 8 12 2 9 10 3 4
The average of all the numbers is 5.45
After sorting the array,
1 2 2 3 3 4 6 8 9 10 12
as the length of the list is an odd number, the median will be the middle number in the sorted list. So the median will be 4.
As 2 and 3 are having the same frequency, the mode will be 2 3.
So the output should be
Mean: 5.45
Median: 4
Mode: 2 3
Sample Input 1
2 4 5 6 7 8 2 4 5 2 3 8
Sample Output 1
Mean: 4.67
Median: 4.5
Mode: 2
Sample Input 2
2 6 3 1 8 12 2 9 10 3 4
Sample Output 2
Mean: 5.45
Median: 4
Mode: 2 3
def find_mean(numbers):
return sum(numbers)/len(numbers)
def find_median(numbers):
if len(numbers)%2 == 0:
return (numbers[(len(numbers)-1)//2] + numbers[(len(numbers)+1)//2])/2
return numbers[len(numbers)//2]
def count_frequency(numbers, number):
frequency = 0
for i in range(len(numbers)):
if numbers[i] == number:
frequency += 1
return frequency
def find_max_frequency(frequencies):
return max(frequencies)
def find_modes(numbers):
frequencies = []
for number in numbers:
frequency = count_frequency(numbers, number)
frequencies.append(frequency)
max_frequency = find_max_frequency(frequencies)
modes = []
for number in numbers:
frequency = count_frequency(numbers, number)
if frequency == max_frequency and number not in modes:
modes.append(number)
return modes
numbers = [2, 6, 3, 1, 8, 12, 2, 9, 10, 3, 4]
numbers.sort()
mean = find_mean(numbers)
median = find_median(numbers)
modes = find_modes(numbers)
print("Mean: ", round(mean,2))
print("Median: ", median)
print("Mode: ", end='')
for mode in modes:
print(mode, end=" ")
Comments
Leave a comment