Answer to Question #186630 in Python for J NAGAMANI

Question #186630

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.


See Sample Input/Output for the output format.


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


The output should be in this function format given below :


def find_mean(num_list):

  # Complete this function


def find_median(num_list):

  # Complete this function



def find_mode(num_list):

  # Complete this function



num_list = list(map(int, input().split()))

# Call the appropriate functions and print the results





1
Expert's answer
2021-04-28T15:49:51-0400
def find_mean(num_list):
    sum = 0
    for n in num_list:
        sum += n
    return (sum / len(num_list))

def find_median(num_list):
    tmp = sorted(num_list)
    size = len(tmp)
    if size % 2:
        return tmp[size // 2]
    else:
        return (tmp[size // 2 - 1] + tmp[size // 2]) / 2

def find_mode(num_list):
    frequency = {}
    for n in num_list:
        if n in frequency:
            frequency[n] += 1
        else:
            frequency[n] = 1

    tmp0 = dict(sorted(frequency.items()))
    tmp1 = [[v, k] for k, v in tmp0.items()]
    tmp2 = sorted(tmp1, reverse=True)
    
    tmp3 = []
    tmp3.append(tmp2[0])
    for v in tmp2[1:]:
        if v[0] == tmp2[0][0]:
            tmp3.append(v)

    tmp4 = []
    for v in tmp3:
        tmp4.append(v[1])

    tmp4.sort()

    return tmp4

num_list = list(map(int, input().split()))

print('Mean:', '{:.2f}'.format(find_mean(num_list)))
print('Median:', '{:.2f}'.format(find_median(num_list)))

mode = find_mode(num_list)
print('Mode:', end=' ')
for i in mode:
    print(i, end=' ')
print()

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