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
python #Program to find median of n integers
#create an empty list list1 = []
#read n from user n = int(input("Enter the number of elements: "))
#read n integers and append to list for i in range(n): num = int(input("Enter element: ")) list1.append(num)
#sort the list using built-in function list1.sort()
#find median if n % 2 == 1: #odd number of elements - middle element median = list1[n // 2] else: #even number of elements - average of two middle elements mid1 = list1[n // 2 - 1] mid2 = list1[n // 2] median = (mid1 + mid2) / 2
print("Sorted list:", list1) print("Median:", median)
Output:
Enter the number of elements: 5 Enter element: 45 Enter element: 89 Enter element: 79 Enter element: 76 Enter element: 55 Sorted list: [45, 55, 76, 79, 89] Median: 76
Explanation
This program reads n integers from the user and stores them in a list using a for loop and append() method, similar to Program 9-4 in the textbook. The list is then sorted using the built-in sort() function as suggested in the hint. To find the median, the program checks if n is odd or even. For odd n, the median is the middle element at position n//2. For even n, the median is the average of the two middle elements at positions n//2-1 and n//2.
Solution Steps
Step 1: Create an empty list and read the value of n from the user.
Step 2: Use a for loop to read n integers and append each element to the list.
Step 3: Sort the list using the built-in sort() function.
Step 4: Check if n is odd or even using the modulus operator (%).
Step 5: If n is odd, median is the middle element at index n//2.
Step 6: If n is even, calculate average of two middle elements at indices n//2-1 and n//2.
Step 7: Display the sorted list and the median value.