Write a program to read a list of n integers and find their median. Note: 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 an built-in function to sort the list
Question
Write a program to read a list of $n$ integers and find their median.
Note: 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 an built-in function to sort the list
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here is a Python program that reads a list of ( n ) integers from the user and computes the median of the list:
def find_median(nums):
# Sort the list
nums.sort()
# Find the length of the list
n = len(nums)
# If the number of elements is odd, return the middle element
if n % 2 != 0:
median = nums[n // 2]
else:
# If the number of elements is even, return the average of the two middle elements
mid1 = nums[n // 2]
mid2 = nums[(n // 2) - 1]
median = (mid1 + mid2) / 2
return median
# Read the list of numbers from the user
n = int(input("Enter the number of elements: "))
nums = []
for i in range(n):
elem = int(input(f"Enter element {i+1}: "))
nums.append(elem)
# Find and print the median
median = find_median(nums)
print(f"The median of the list is: {median}")
Explanation:
The
find_median
function takes a list of integers as input and sorts it.The median is found by checking if the length of the list (
n
) is odd or even:If odd, the middle element is returned.
If even, the average of the two middle elements is returned.
The user is prompted to enter the number of elements and then the individual elements of the list.
Finally, the program computes and prints the median of the list.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month