Describe how spread out a list of numbers is, in several ways.
What to build
A program that prints four measures of spread.
Requirements
- Print
range R,IQR Q,population sd Pandsample sd S, each to 2 decimal places. - Quartiles: sort the data; the lower half is the values before the middle and the upper half those after it (an odd count leaves out the middle value); Q1 and Q3 are the medians of the halves.
Input
One line: whole numbers separated by spaces.
Output
Four lines.
Constraints
4 to 1000 numbers.
Example
Input:
62 70 70 75 81 88 91
Output:
range 29.00
IQR 18.00
population sd 9.71
sample sd 10.48
Why it works
The range depends only on the two extremes, the interquartile range on the middle half, and the standard deviations on every value, so they react very differently to outliers.
Examples
Example 1 · Input
62 70 70 75 81 88 91
Expected output
range 29.00 IQR 18.00 population sd 9.71 sample sd 10.48
Example 2 · Input
1 2 3 4
Expected output
range 3.00 IQR 2.00 population sd 1.12 sample sd 1.29
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Q1 is the median of the values below the middle and Q3 the median of those above it; with an odd count, leave the middle value out of both halves.
Hint 2
Population SD divides the squared distances by n, sample SD by n − 1.
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
lower, upper = nums[: n // 2], nums[(n + 1) // 2 :]
mean = sum(nums) / n
squares = sum((x - mean) ** 2 for x in nums)
print(f"range {nums[-1] - nums[0]:.2f}")
print(f"IQR {median(upper) - median(lower):.2f}")
print(f"population sd {(squares / n) ** 0.5:.2f}")
print(f"sample sd {(squares / (n - 1)) ** 0.5:.2f}")