Nearest-Rank Latency Percentile
Problem Statement
Compute a latency percentile from a list of samples using the nearest-rank method, the standard for p50/p95/p99 dashboards.
Background
Sort the n samples ascending. The nearest-rank percentile p (in 0..100) is the value at 1-based rank ceil(p/100 * n) (rank at least 1). This returns an actual observed sample, not an interpolated value.
Your Task
def percentile(samples, p):
Return the sample at the nearest rank for percentile p.
Input Format
- samples (non-empty list of numbers), p (number in 0..100).
Output Format
- A number (one of the samples).
Sample
print(percentile([10, 20, 30, 40, 50], 95))
Output:
50
Example
print(percentile([10, 20, 30, 40, 50], 95))
50
- Sort the input samples in ascending order to establish the rank positions: , where .
- Calculate the target rank using the nearest-rank formula with : .
- Ensure the rank is at least 1 (it is already 5) and convert this 1-based rank to a 0-based index for retrieval: .
- Retrieve the value at index 4 from the sorted list, which corresponds to the 5th element.
- The final output is 50
Constraints
- Sort ascending; rank =
ceil(p/100 * n), clamped to at least 1. - Return the value at that 1-based rank.
samplesis non-empty.