In: Computer Science
python3
Let x0,...,xn−1 be n numbers stored in the list x. The median of x, denoted median(x) is the “middle”-value of the numbers in x in the sense that half of the numbers in x are less than the median and the other half of the numbers in x are greater than the median. Let y denote a copy of x sorted in ascending order. Then median(x)=(y[n+1 2 −1] if n is oddy [n 2−1]+y[n 2] 2 if n is even. Complete the function my_median with the following specifications: • It that takes in one parameter, x, which is a list of numbers. • It returns median(x). • Do not alter x. Evaluating your function my_median(x) should not change the value of the list x. • Do not use Python’s built-in median function.


Raw_code:
# my_median function
def my_median(x):
# creating a sorted list of x and assigning to y
y = sorted(x)
# calculating length of list-x and assigning the length to n
n = len(x)
# checking whether the n is even or not by modular
division
if (n%2) == 0:
# if even returing the average of middle two elements of y
return (y[n//2 -1] + y[n//2])/2
else:
# returning the middle element of y
return y[(n+1)//2 -1]
x = [2, 4, 1, 3 ,5, 6]
print("x :", x, " Median of x: ", my_median(x))
x = [4, 5, 2, 1, 3]
print("x :", x, " Median of x: ", my_median(x))