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
The first line of output should contain the mean, round off the value to 2 decimal places.
The second line of output should contain the median, round off the value to 2 decimal places.
The third line of output should contain the mode.
Mean should always be a float value.
Median should be a float value when there are even number of elements, otherwise should be an integer value.
See Sample Input/Output for the output format.Explanation
2 4 5 6 7 8 2 4 5 2 3 8
The average of all the numbers is 4.67.
After sorting the array,
2 2 2 3 4 4 5 5 6 7 8 8
def mean(L):
return sum(L)/len(L)
def median(L):
n = len(L)
m = n//2
if n % 2 == 1:
return L[m]
else:
return (L[m-1]+L[m]) / 2
def mode(L):
modeVal = L[0]
curVal = L[0]
count = 1
maxCount = 1
for i in range(1, len(L)):
if L[i] == curVal:
count += 1
else:
if count > maxCount:
maxCount = count
modeVal = curVal
curVal = L[i]
count = 1
return modeVal
def main():
line = input('Enter a list of integers: ')
L = [int(s) for s in line.split()]
L.sort()
print(f'Mean is {mean(L):.2f}')
print('Median is', median(L))
print('Mode is', mode(L))
if __name__ == '__main__':
main()
Comments
Leave a comment