Answer to Question #184967 in Python for jayanth

Question #184967

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.

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





1
Expert's answer
2021-04-24T06:11:44-0400
while True:
	n = input('enter space-separated integers or -999 to exit\n')
	
	if n == '-999':
		break
	elif len(n) == 0:
		print('no data entered')
		continue
	else:
		try:
			list_of_n = list(map(int,n.split()))
		except:
			print('wrong input. enter space-separated integers')
			continue
	
	#calculate the average of all numbers
	mean = round(sum(list_of_n)/len(list_of_n),2)
	
	#calculate the mid point value in the sorted list
	if len(list_of_n) % 2 == 0:
		index_1 = len(list_of_n) // 2 - 1
		index_2 = len(list_of_n) // 2
		median = round((sorted(list_of_n)[index_1] + sorted(list_of_n)[index_2])  / 2, 2)
	else:
		index = len(list_of_n) // 2 
		median = sorted(list_of_n)[index]


	#calculate the most common value in the list
	uniq_list = list(set(list_of_n))
	if len(uniq_list) == len(list_of_n):
		list_of_el = ['list of unique integers']
	else:
		max_frequency = 0
		list_of_el = list()
		for el in uniq_list:
			if list_of_n.count(el) > max_frequency:
				max_frequency = list_of_n.count(el)
				list_of_el = [el]
			elif list_of_n.count(el) == max_frequency:
				list_of_el.append(el)


	print('Mean:', mean)
	print('Median:', median)
	print('Mode:', *list_of_el)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS