Answer to Question #184120 in Python for suresh

Question #184120
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











1
Expert's answer
2021-04-22T02:24:32-0400
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()

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