preamble
The median is a value that divides a collection of values into two equal parts. If the number of list data is odd, the one in the middle of the list is the median of the list data; if the number of list data is even, the arithmetic mean of the 2 data in the middle of the list is the median of the list data. In this task, you will be given a non-empty array (X) containing natural numbers. You must find the median by dividing it into upper and lower parts.
Input: A list of integers (int) as an array (list).
Output: Median of the array (int, float).
typical example
get_median([1, 2, 3, 4, 5]) == 3 get_median([3, 1, 2, 5, 3]) == 3 get_median([1, 300, 2, 200, 1]) == 2 get_median([3, 6, 20, 99, 10, 15]) == 12.5
How to use:The median is used in probability theory and statistics, and it has a significant value in skewed distributions. For example:We want to know the average wealth of people from a set of data - 100 people earn $100 a month and 10 people earn $1,000,000 a month. If we calculate the average, we get $91,000. That's a strange value that doesn't show us the true picture at all. So in this case, the median would give us a more useful value and a better description.
Prerequisite. 1 < len(data) ≤ 1000 all(0 ≤ x < 10 ** 6 for x in data)
Common Methods:
Sort the list and calculate the median for different cases where the list length is odd or even.
def get_median(data): data = sorted(data) size = len(data) if size % 2 == 0: # Determine that the list length is even median = (data[size//2]+data[size//2-1])/2 data[0] = median if size % 2 == 1: # Determine that the list length is odd median = data[(size-1)//2] data[0] = median return data[0]
Best method:
This solution is very clever in that it takes advantage of the property of taking the inverse of a number and summing to 1 to get the median of the list by using the negative index of the list.
treat (sb a certain way)return (data[half] + data[~half]) / 2
The explanation:
Sorting yields the sequence [1,2,3,4,5,6], whose list length is even, and whose median is determined by the two middle elements of the list, 3 (indexed 2),4 (indexed 3). And the negative index of element 4 is -3, which is exactly the inverse of index 2.
Sorting yields the sequence [1,2,3,4,5], whose list length is odd and whose median is determined by the middle element of the list, 3 (indexed 2 and negatively indexed -3). It still conforms to the code.
def get_median(data): () half = len(data) // 2 return (data[half] + data[~half]) / 2
summarize
Above is Python implementation to get the median of the list of all the content, I hope that the content of this article on everyone to learn python can help.