Build a descriptive statistics calculator that computes the mean, median, mode, variance, and standard deviation of a given dataset.
def descriptive_stats(data):
n = len(data)
if n == 0:
return {}
# Mean
mean = sum(data) / n
# Median
sorted_data = sorted(data)
if n % 2 == 1:
median = sorted_data[n // 2]
else:
median = (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2
# Mode
counts = {}
for val in data:
counts[val] = counts.get(val, 0) + 1
max_count = max(counts.values())
mode = min(val for val, cnt in counts.items() if cnt == max_count)
# Variance and Standard Deviation (population)
variance = sum((x - mean) ** 2 for x in data) / n
std_dev = variance ** 0.5
return {
"mean": round(mean, 4),
"median": round(median, 4),
"mode": mode,
"variance": round(variance, 4),
"std_dev": round(std_dev, 4)
}