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 second 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-seperated 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 medium,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.
INPUT
2 2 2 3 4 4 5 5 6 7 8 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
The answer to your question.
number_str=input("Enter whole numbers separated by spaces: \n")
num=[]
for s in number_str.split():
num.append(int(s))
num.sort()
print(num)
print("Mean: "+str(round(sum(num)/len(num),2)))
index = len(num)//2
if len(num)%2:
median=num[index]
else:
median=sum(num[index-1:index+1])/2
print("Median: "+str(median))
nx=num[0]
count=[]
f=0
for n in num:
if n==nx:
f=f+1
else:
count.append((nx,f))
f=1
nx=n
count.append((nx,f))
mode=[]
nx=0
for n in count:
if n[1]>nx:
nx=n[1]
for n in count:
if n[1]==nx:
mode.append(str(n[0]))
print("Mode: "+" ".join(mode))
Comments
Leave a comment