Compute the quartiles the way NumPy and pandas do by default.
What to build
A program that prints Q1, the median, Q3 and the IQR.
Requirements
- Sort the values. The p quantile is at position (n − 1) × p; if that position is not a whole number, interpolate linearly between the values at the positions on either side.
- Print
Q1: A,median: B,Q3: CandIQR: D, each with two decimals.
Input
One line of numbers separated by spaces.
Output
Four lines.
Constraints
1 to 1000 numbers.
Example
Input:
1 2 3 4 5 6 7 8
Output:
Q1: 2.75
median: 4.50
Q3: 6.25
IQR: 3.50
Why it works
Linear interpolation gives a quartile even when it falls between two values, and it matches the numbers most analysis libraries report.
Examples
Example 1 · Input
1 2 3 4 5 6 7 8
Expected output
Q1: 2.75 median: 4.50 Q3: 6.25 IQR: 3.50
Example 2 · Input
7
Expected output
Q1: 7.00 median: 7.00 Q3: 7.00 IQR: 0.00
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The p quantile is at position (n − 1) × p of the sorted values.
Hint 2
Between positions i and i + 1, add the fractional part times the gap between the two values.
Solution
Show one correct solution (try it yourself first)
values = sorted(float(v) for v in input().split())
n = len(values)
def quantile(p):
pos = (n - 1) * p
i = int(pos)
if i + 1 >= n:
return values[i]
return values[i] + (pos - i) * (values[i + 1] - values[i])
q1, med, q3 = quantile(0.25), quantile(0.5), quantile(0.75)
print(f"Q1: {q1:.2f}")
print(f"median: {med:.2f}")
print(f"Q3: {q3:.2f}")
print(f"IQR: {q3 - q1:.2f}")