Question 4 of 6intermediate🔧 ApplyLong Answer5 marks

Write a program using user defined functions that accepts a List of numbers as an argument and finds its median. (Hint: Use bubble sort to sort the accepted list. If there are odd number of terms, the median is the center term. If there are even number of terms, add the two middle terms and divide by 2 get median)

Correct Answer

def bubble_sort(numList): n = len(numList) for i in range(n-1): for j in range(0, n-i-1): if numList[j] > numList[j+1]: numList[j], numList[j+1] = numList[j+1], numList[j] return numList

def find_median(numList): sorted_list = bubble_sort(numList) n = len(sorted_list)

if n % 2 == 1:
    median = sorted_list[n // 2]
else:
    mid1 = sorted_list[n // 2 - 1]
    mid2 = sorted_list[n // 2]
    median = (mid1 + mid2) / 2

return median

Main program

numList = eval(input("Enter a list of numbers: ")) median = find_median(numList) print("Median:", median)

Exercise: EXERCISE | Q: 4 | (Page Page 13)
For More Understanding

Explanation

The question requires writing a program with user-defined functions to find the median of a list. The solution uses bubble sort as specified in the hint. The bubble_sort function sorts the list by comparing adjacent elements and swapping them if they are in wrong order. After sorting, the find_median function checks if the number of elements is odd or even. For odd count, it returns the center element at index n//2. For even count, it calculates the average of the two middle elements at indices n//2-1 and n//2.

Solution Steps

  1. Step 1: Define bubble_sort() function to sort the list in ascending order using adjacent element comparison and swapping.

  2. Step 2: Define find_median() function that first calls bubble_sort() to sort the accepted list.

  3. Step 3: Calculate length of sorted list using len() function.

  4. Step 4: Check if number of terms is odd (n%2==1) - return center term at index n//2.

  5. Step 5: If number of terms is even - add two middle terms and divide by 2 to get median.