np.percentile uses linear interpolation by default. Compute the same values.
What to build
A program that prints percentiles the way np.percentile does by default.
Requirements
- For each requested q, in order, print
pQ = V, with Q as given and V to two decimals. - Use the sorted data and position (n − 1) × q ÷ 100, interpolating linearly between the two neighbouring values.
Input
Line 1: the data, numbers separated by spaces. Line 2: the percentiles to compute, between 0 and 100.
Output
One line per percentile.
Constraints
1 to 1000 data values; 1 to 20 percentiles.
Example
Input:
1 2 3 4
25 50 75
Output:
p25 = 1.75
p50 = 2.50
p75 = 3.25
Why it works
Linear interpolation treats the sorted values as points spaced evenly from position 0 to n − 1 and joins them with straight lines, so every percentile has one well-defined value.
Examples
1 2 3 4 25 50 75
p25 = 1.75 p50 = 2.50 p75 = 3.25
10 0 100
p0 = 10.00 p100 = 10.00
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Sort the data, then compute pos = (n − 1) × q ÷ 100.
Hint 2
Take the value at int(pos) and move the fraction pos − int(pos) of the way to the next value.
Solution
Show one correct solution (try it yourself first)
data = sorted(float(x) for x in input().split())
for q in input().split():
pos = (len(data) - 1) * float(q) / 100
low = int(pos)
high = min(low + 1, len(data) - 1)
value = data[low] + (pos - low) * (data[high] - data[low])
print(f"p{q} = {value:.2f}")