Data Visualization: Find what the mean hides

A single extreme value moves the mean but not the median. Detect when that happens, before a chart would show it.

What to build

A program that reports the mean, the median, the value farthest from the median, and whether the mean is being pulled.

Requirements

  • Print mean: M and median: D with two decimals, then farthest from the median: V, the value with the largest distance from the median (the first one in input order if several tie), written with Python's :g format.
  • Then print the mean is pulled by extreme values if the mean and median differ by more than a tenth of the range (largest minus smallest value), and otherwise mean and median agree.

Input

One line of numbers separated by spaces.

Output

Four lines.

Constraints

1 to 1000 numbers.

Example

Input:

3 4 5 5 6 40

Output:

mean: 10.50
median: 5.00
farthest from the median: 40
the mean is pulled by extreme values

Why it works

The median depends only on the middle of the sorted data, so a gap between it and the mean is a quick sign of a long tail or an outlier, which is exactly what a histogram or box plot would show.

Examples

Example 1 · Input
3 4 5 5 6 40
Expected output
mean: 10.50
median: 5.00
farthest from the median: 40
the mean is pulled by extreme values
Example 2 · Input
1 2 3 4 5
Expected output
mean: 3.00
median: 3.00
farthest from the median: 1
mean and median agree

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

Hints

Hint 1

Sort a copy of the values to find the median.

Hint 2

Compare the gap between mean and median with a tenth of the range.

Solution

Show one correct solution (try it yourself first)
values = [float(v) for v in input().split()]
n = len(values)
mean = sum(values) / n
ordered = sorted(values)
middle = n // 2
median = ordered[middle] if n % 2 else (ordered[middle - 1] + ordered[middle]) / 2
farthest = values[0]
for v in values:
    if abs(v - median) > abs(farthest - median):
        farthest = v
spread = max(values) - min(values)
print(f"mean: {mean:.2f}")
print(f"median: {median:.2f}")
print(f"farthest from the median: {farthest:g}")
if abs(mean - median) > 0.1 * spread:
    print("the mean is pulled by extreme values")
else:
    print("mean and median agree")

Lesson: Why visualize data →