import csv
import html
import math
from collections import defaultdict
def quantile(values, fraction):
values = sorted(values)
pos = (len(values) - 1) * fraction
lo, hi = math.floor(pos), math.ceil(pos)
return values[lo] + (values[hi] - values[lo]) * (pos - lo)
def pearson(xs, ys):
ax, ay = sum(xs) / len(xs), sum(ys) / len(ys)
num = sum((x - ax) * (y - ay) for x, y in zip(xs, ys))
den = math.sqrt(sum((x - ax) ** 2 for x in xs) * sum((y - ay) ** 2 for y in ys))
return num / den if den else 0.0
def write_csv(path, rows):
with open(path, "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print("1/4 Read Boston data and detect IQR outliers")
lines = [line.split() for line in open("BostonHousing.txt", encoding="utf-8-sig") if line.strip()]
header = lines[0]
boston = [dict(zip(header, values)) for values in lines[1:] if len(values) == len(header)]
prices = [float(row["medv"]) for row in boston]
q1, q3 = quantile(prices, .25), quantile(prices, .75)
low, high = q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1)
outliers = [row for row in boston if not low <= float(row["medv"]) <= high]
clean = [row.copy() for row in boston if low <= float(row["medv"]) <= high]
for row in clean:
row["rm_rounded"] = str(math.floor(float(row["rm"]) + 0.5))
write_csv("boston_clean.csv", clean)
print(f"Boston rows={len(boston)}, outliers={len(outliers)}, retained={len(clean)}")
print("2/4 Compute Pearson correlations and room-group means")
correlations = {
name: pearson([float(row[name]) for row in boston], prices)
for name in header if name != "medv"
}
top = sorted(correlations, key=lambda name: (-abs(correlations[name]), name))[:3]
rooms = defaultdict(list)
for row in clean:
rooms[int(row["rm_rounded"])].append(float(row["medv"]))
means = {room: sum(values) / len(values) for room, values in rooms.items()}
print("3/4 Clean Titanic and group survival outcomes")
with open("titanic.csv", newline="", encoding="utf-8-sig") as handle:
titanic = list(csv.DictReader(handle))
ages = [float(row["age"]) for row in titanic if row.get("age", "").strip()]
age_fill = quantile(ages, .5)
for row in titanic:
row["age"] = row.get("age") or str(age_fill)
row["deck"] = row.get("deck") or "Unknown"
row["is_alone"] = str(int(float(row["sibsp"]) + float(row["parch"]) == 0)).lower()
write_csv("titanic_clean.csv", titanic)
groups = defaultdict(list)
for row in titanic:
groups[(row["sex"], row["class"])].append(int(row["survived"]))
rates = {key: sum(values) / len(values) for key, values in groups.items()}
print("4/4 Render report with offline SVG charts")
def table(identifier, columns, rows):
headings = "".join(f"