Flag the values that lie far from the rest, and see how much they move the mean.
What to build
A program that applies the 1.5 × IQR rule.
Requirements
- Quartiles as before: sort, take the values before and after the middle (an odd count leaves the middle out), and use the median of each half.
- Print
Q1 AandQ3 B(2 decimal places),fences L to U(2 decimal places),outliersfollowed by the outliers in increasing order (oroutliers none), thenmean with Mandmean without N, the mean of all values and of the non-outliers (2 decimal places).
Input
One line: whole numbers separated by spaces.
Output
Six lines.
Constraints
4 to 1000 numbers.
Example
Input:
62 70 70 75 81 88 91 11
Output:
Q1 66.00
Q3 84.50
fences 38.25 to 112.25
outliers 11
mean with 68.50
mean without 76.71
Why it works
The quartiles are themselves resistant to extreme values, so fences built from them are not dragged out by the very outliers they are meant to catch.
Examples
Example 1 · Input
62 70 70 75 81 88 91 11
Expected output
Q1 66.00 Q3 84.50 fences 38.25 to 112.25 outliers 11 mean with 68.50 mean without 76.71
Example 2 · Input
1 2 3 4
Expected output
Q1 1.50 Q3 3.50 fences -1.50 to 6.50 outliers none mean with 2.50 mean without 2.50
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Find Q1 and Q3 as in the medians of the lower and upper halves, then the fences Q1 − 1.5 × IQR and Q3 + 1.5 × IQR.
Hint 2
An outlier is strictly outside the fences.
Solution
Show one correct solution (try it yourself first)
nums = sorted(int(x) for x in input().split())
n = len(nums)
def median(values):
m = len(values) // 2
return values[m] if len(values) % 2 else (values[m - 1] + values[m]) / 2
q1, q3 = median(nums[: n // 2]), median(nums[(n + 1) // 2 :])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outliers = [x for x in nums if x < low or x > high]
kept = [x for x in nums if low <= x <= high]
print(f"Q1 {q1:.2f}")
print(f"Q3 {q3:.2f}")
print(f"fences {low:.2f} to {high:.2f}")
print("outliers", " ".join(map(str, outliers)) if outliers else "none")
print(f"mean with {sum(nums) / n:.2f}")
print(f"mean without {sum(kept) / len(kept):.2f}")