Data science: Find outliers with the IQR rule

Some values are far from the rest. Find them with the standard 1.5 × IQR rule.

What to build

A program that finds outliers in a list of numbers.

Requirements

  • Compute Q1 and Q3 as medians of the lower and upper halves of the sorted values (leaving out the middle value when n is odd), and IQR = Q3 − Q1.
  • Print Q1: X, Q3: X, IQR: X, fences: LOW to HIGH and outliers: a, b, ... (the values below LOW or above HIGH, in input order) or outliers: none. Print numbers as whole numbers when they are, otherwise with at most two decimals.

Input

Line 1: n. Line 2: n numbers separated by spaces.

Output

Five lines.

Constraints

4 ≤ n ≤ 1000.

Example

Input:

10
12 15 11 14 12 45 12 16 14 13

Output:

Q1: 12
Q3: 15
IQR: 3
fences: 7.5 to 19.5
outliers: 45

Why it works

The fences are built from the quartiles, which extreme values barely move, so the rule finds values that are unusual compared with the middle of the data rather than with an average they have already distorted.

Examples

Example 1 · Input
10
12 15 11 14 12 45 12 16 14 13
Expected output
Q1: 12
Q3: 15
IQR: 3
fences: 7.5 to 19.5
outliers: 45
Example 2 · Input
4
1 2 3 4
Expected output
Q1: 1.5
Q3: 3.5
IQR: 2
fences: -1.5 to 6.5
outliers: none

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

Hints

Hint 1

Use the median-of-halves quartiles: the lower half is s[:n // 2] and the upper half s[(n + 1) // 2:].

Hint 2

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

Solution

Show one correct solution (try it yourself first)
n = int(input())
values = [float(x) for x in input().split()]
s = sorted(values)


def median(v):
    m = len(v) // 2
    return v[m] if len(v) % 2 else (v[m - 1] + v[m]) / 2


def show(x):
    return f"{x:.2f}".rstrip("0").rstrip(".")


q1 = median(s[: n // 2])
q3 = median(s[(n + 1) // 2 :])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outliers = [v for v in values if v < low or v > high]
print("Q1:", show(q1))
print("Q3:", show(q3))
print("IQR:", show(iqr))
print(f"fences: {show(low)} to {show(high)}")
print("outliers:", ", ".join(show(v) for v in outliers) if outliers else "none")

Lesson: Descriptive statistics →