Data Visualization: Fences, whiskers and outliers

Find the values a box plot would draw separately, and where its whiskers end.

What to build

A program that computes Tukey's fences, the whisker ends and the outliers.

Requirements

  • Compute Q1 and Q3 by linear interpolation at position (n − 1) × p of the sorted values, and IQR = Q3 − Q1.
  • Print fences: LOW to HIGH with two decimals, then whiskers: A to B with the smallest and largest values inside the fences (inclusive), written with :g, then outliers: and the values outside the fences in increasing order separated by , (with :g), or outliers: none.

Input

One line of numbers separated by spaces.

Output

Three lines.

Constraints

1 to 1000 numbers.

Example

Input:

31 52 61 64 67 70 71 73 75 78 80 84 97

Output:

fences: 43.00 to 99.00
whiskers: 52 to 97
outliers: 31

Why it works

The fences scale with the spread of the middle half of the data, so what counts as unusual depends on how variable the data is, not on a fixed distance.

Examples

Example 1 · Input
31 52 61 64 67 70 71 73 75 78 80 84 97
Expected output
fences: 43.00 to 99.00
whiskers: 52 to 97
outliers: 31
Example 2 · Input
1 2 3 4 5 6 7 8
Expected output
fences: -2.50 to 11.50
whiskers: 1 to 8
outliers: none

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The fences are Q1 − 1.5 × IQR and Q3 + 1.5 × IQR.

Hint 2

The whiskers end at the smallest and largest values that are inside the fences (fences included).

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, q3 = quantile(0.25), quantile(0.75)
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
inside = [v for v in values if low <= v <= high]
outside = [v for v in values if v < low or v > high]
print(f"fences: {low:.2f} to {high:.2f}")
print(f"whiskers: {inside[0]:g} to {inside[-1]:g}")
print("outliers: " + (", ".join(f"{v:g}" for v in outside) if outside else "none"))

Lesson: Box plots and quartiles →