Answer to Question #316824 in Python for MEDIAN2

Question #316824

Median


given a list of integers,write a program to print the mean,median and mode 

median - the mid point value in the sorted list.


input 

the input will be a single line of containing space-separated integers.


output

the second line of output should contain the median, round off the value to 2 decimal places.

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 


for example, if the given list of integers are 

2 6 3 8 12 2 9 10 3 4

the average of all the numbers is 4.67.

after sorting the array,

1 2 2 3 3 4 6 8 9 10 12

as the length of the list is an odd number, the median will be middle numbers in the sorted list.so the median will be 4

so the output should be


Median: 4


1
Expert's answer
2022-03-26T05:44:52-0400
def median(L):
    L.sort()
    n = len(L)
    if n%2 == 1:
        res = L[n//2]
    else:
        res = (L[n//2-1] + L[n//2]) / 2
    return res


def main():
    line = input()
    L = [int(s) for s in line.split()]
    m = median(L[:])
    if type(m) is int:
        print(m)
    else:
        print(f'{m:.2f}')


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