Five numbers describe a whole column: the minimum, the quartiles, the median and the maximum.
What to build
A program that prints the five-number summary of a list of numbers.
Requirements
- Find the median of the sorted values. Q1 is the median of the lower half and Q3 the median of the upper half, leaving out the middle value when n is odd; when n is 1, Q1 and Q3 are that value.
- Print
min: X,Q1: X,median: X,Q3: Xandmax: X, each as a whole number if it is one and otherwise with at most two decimals (no trailing zeros).
Input
Line 1: n. Line 2: n numbers separated by spaces.
Output
Five lines.
Constraints
1 ≤ n ≤ 1000.
Example
Input:
7
6 3 9 1 7 4 8
Output:
min: 1
Q1: 3
median: 6
Q3: 8
max: 9
Why it works
Quartiles are medians of the halves, so the same small median function gives all three cut points, and the five numbers together show the centre, the spread of the middle half and the extremes.
Examples
Example 1 · Input
7 6 3 9 1 7 4 8
Expected output
min: 1 Q1: 3 median: 6 Q3: 8 max: 9
Example 2 · Input
6 9 2 7 4 5 4
Expected output
min: 2 Q1: 4 median: 4.5 Q3: 7 max: 9
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Sort the values; the lower half is s[:n // 2] and the upper half is s[(n + 1) // 2:].
Hint 2
f"{x:.2f}".rstrip("0").rstrip(".") prints 3.50 as 3.5 and 4.00 as 4.
Solution
Show one correct solution (try it yourself first)
n = int(input())
s = sorted(float(x) for x in input().split())
def median(values):
m = len(values) // 2
return values[m] if len(values) % 2 else (values[m - 1] + values[m]) / 2
def show(x):
return f"{x:.2f}".rstrip("0").rstrip(".")
if n == 1:
q1 = q3 = s[0]
else:
q1 = median(s[: n // 2])
q3 = median(s[(n + 1) // 2 :])
print("min:", show(s[0]))
print("Q1:", show(q1))
print("median:", show(median(s)))
print("Q3:", show(q3))
print("max:", show(s[-1]))