Find the median of a line of numbers, including in the unusual cases.
What to build
A function that has been thought through for every edge case.
Requirements
- Write
median(nums), which returns the middle value of the sorted numbers. - For an even count, it returns the average of the two middle values.
- If the line is empty, print
no data. - Print a median that is a whole number with no decimals, and any other with one decimal.
Input
One line of whole numbers separated by spaces, which may be empty.
Output
One line.
Constraints
There are at most 1000 numbers, from -1000 to 1000.
Example
Input:
3 1 2
Output:
2
Why it works
Sorting a copy leaves the caller's list alone. The empty line would make the code index past the end, which is the bug this exercise is designed to catch.
Examples
Example 1 · Input
3 1 2
Expected output
2
Example 2 · Input
1 2 3 4
Expected output
2.5
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Sort a copy of the numbers first.
Hint 2
For an even count, average the two middle values.
Hint 3
Handle the empty line before anything else.
Solution
Show one correct solution (try it yourself first)
def median(nums):
ordered = sorted(nums)
middle = len(ordered) // 2
if len(ordered) % 2 == 1:
return ordered[middle]
return (ordered[middle - 1] + ordered[middle]) / 2
nums = [int(x) for x in input().split()]
if not nums:
print("no data")
else:
result = median(nums)
if result == int(result):
print(int(result))
else:
print(f"{result:.1f}")