📅  最后修改于: 2023-12-03 14:58:24.224000             🧑  作者: Mango
GATE (Graduate Aptitude Test in Engineering) is a national level entrance exam for engineering graduates in India who seek admission into postgraduate programs. The GATE Mock 2017 is a mock test designed to help students prepare for the GATE exam. Problem 4 of the mock test challenges programmers to solve a problem related to finding the median of a given set of numbers.
The problem statement goes like this:
"A median is a value separating the higher half from the lower half of a data sample. If the data set has an odd number of observations, the number in the middle is the median. For example, in the data set {1, 3, 3, 6, 7, 8, 9}, the median is 6, which is the fourth value. If the data set has an even number of observations, there is no distinct middle value and the median is usually defined to be the average of the two middle values. For example, in the data set {1, 2, 3, 4, 5, 6, 8, 9}, the median is (4 + 5) / 2 = 4.5."
Your task is to write a Python function that takes a list of integers as input and returns the median of the list.
To solve this problem, we need to first understand what a median is. As described in the problem statement, the median of a list of numbers can be found by sorting the list and picking the middle element(s). If the list has an odd length, there will be exactly one middle element, whereas if the list has an even length, there will be two middle elements. In the latter case, we need to take the average of these two elements to get the median.
We can start by writing a Python function that sorts the input list using the built-in sorted()
function:
def find_median(lst):
sorted_lst = sorted(lst)
print(sorted_lst)
We can then find the length of the list using the len()
function and use some conditional statements to pick the middle element(s) and compute the median:
def find_median(lst):
sorted_lst = sorted(lst)
n = len(sorted_lst)
if n % 2 == 0:
# list has even length
mid_right = n // 2
mid_left = mid_right - 1
median = (sorted_lst[mid_left] + sorted_lst[mid_right]) / 2
else:
# list has odd length
mid = n // 2
median = sorted_lst[mid]
return median
We can now call this function with some sample inputs and test it:
lst1 = [1, 3, 3, 6, 7, 8, 9]
assert find_median(lst1) == 6
lst2 = [1, 2, 3, 4, 5, 6, 8, 9]
assert find_median(lst2) == 4.5
In conclusion, the problem of finding the median of a list of integers can be solved by sorting the list and picking the middle element(s), as described in the problem statement. This can be done in Python using the built-in sorted()
function and some conditional statements to handle different cases of list length.