CameraIcon
CameraIcon
SearchIcon
MyQuestionIcon
MyQuestionIcon
281
You visited us 281 times! Enjoying our articles? Unlock Full Access!
Question

Write a program to read a list of n integers and find their median.
The median value of a list of values is the middle one when they are arranged in order. If there are two middle values then take their average.
Hint: You can use a built-in function to sort the list

Open in App
Solution

Program:
def medianValue(list1):
#Sorting the list
list1.sort()
#Checking the last index
indexes = len(list1)
if(indexes%2 == 0):
#if the number of elements is even, then we have to find average of two middle values
num1 = (indexes) // 2 #first middle element
num2 = (indexes // 2) + 1 #second middle element
#Calculating median as average of the two
med = (list1[num1 - 1] + list1[num2 - 1]) / 2
return med
else:
#if number of elements is odd, then we have to return the element at middle index

middle = (indexes - 1) // 2
med = list1[middle]
return med

#defining empty list
list1 = list()
#Getting input of number of elements to be added in the list
inp = int(input("How many elements do you want to add in the list? "))
#Getting the input of elements from user
for i in range(inp):
a = int(input("Enter the elements: "))
list1.append(a)
#Printing the list
print("The median value is",medianValue(list1))


OUTPUT:
How many elements do you want to add in the list? 6
Enter the elements: 1
Enter the elements: 2
Enter the elements: 3
Enter the elements: 4
Enter the elements: 5
Enter the elements: 6
The median value is 3.5

flag
Suggest Corrections
thumbs-up
1
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Median
MATHEMATICS
Watch in App
Join BYJU'S Learning Program
CrossIcon