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"{html.escape(str(value))}" for value in columns) body = "".join( "" + "".join(f"{html.escape(str(value))}" for value in row) + "" for row in rows ) return f'{headings}{body}
' def svg_text(x, y, label, anchor="middle", extra=""): return (f'' f'{html.escape(str(label))}') def scatter_chart(rows): xs = [float(row["rm"]) for row in rows] ys = [float(row["medv"]) for row in rows] xmean, ymean = sum(xs) / len(xs), sum(ys) / len(ys) denominator = sum((x - xmean) ** 2 for x in xs) slope = sum((x - xmean) * (y - ymean) for x, y in zip(xs, ys)) / denominator if denominator else 0 intercept = ymean - slope * xmean xmin, xmax = min(xs), max(xs) xlow, xhigh = (xmin, xmax) if xmin != xmax else (xmin - .5, xmax + .5) # Include the complete fitted segment in the linear y scale, with marker clearance. ylow = min(min(ys), slope * xmin + intercept, slope * xmax + intercept) yhigh = max(max(ys), slope * xmin + intercept, slope * xmax + intercept) padding = max((yhigh - ylow) * .08, .5) ylow, yhigh = ylow - padding, yhigh + padding left, right, top_edge, bottom = 68, 494, 22, 238 def xpx(value): return left + (right - left) * (value - xlow) / (xhigh - xlow) def ypx(value): return bottom - (bottom - top_edge) * (value - ylow) / (yhigh - ylow) parts = [''] for index in range(5): xvalue = xlow + (xhigh - xlow) * index / 4 yvalue = ylow + (yhigh - ylow) * index / 4 x, y = xpx(xvalue), ypx(yvalue) parts.append(f'') parts.append(f'') parts.append(svg_text(x, bottom + 22, f"{xvalue:.2f}")) parts.append(svg_text(left - 10, y + 4, f"{yvalue:.2f}", "end")) parts.append(f'') parts.append(svg_text((left + right) / 2, 287, "rm", extra='class="axis-title"')) parts.append(svg_text(18, 130, "medv", extra='class="axis-title" transform="rotate(-90 18 130)"')) parts.append(f'') for x, y in zip(xs, ys): parts.append(f'') parts.append('') return "".join(parts) def survival_chart(group_rates): groups = sorted(group_rates.items()) left, right, top_edge, bottom = 68, 500, 22, 212 slot = (right - left) / len(groups) bar_width = min(40, slot * .58) parts = [''] for rate in (0, .25, .5, .75, 1): y = bottom - (bottom - top_edge) * rate parts.append(f'') parts.append(svg_text(left - 10, y + 4, f"{rate:.0%}", "end")) parts.append(f'') parts.append(svg_text(18, 118, "Survival rate", extra='class="axis-title" transform="rotate(-90 18 118)"')) for index, ((sex, category), rate) in enumerate(groups): center = left + slot * (index + .5) height = (bottom - top_edge) * rate parts.append(f'') parts.append(svg_text(center, bottom - height - 7, f"{rate:.0%}")) # Labels exist independently of bar height, including zero-survival groups. parts.append(f'' f'{html.escape(sex)} ' f'{html.escape(category)}') parts.append(svg_text((left + right) / 2, 287, "Passenger group (sex × class)", extra='class="axis-title"')) parts.append('') return "".join(parts) style = """ * { box-sizing: border-box; } body { margin: 0; padding: 24px; background: #f3f6fa; color: #1e3044; font-family: system-ui, -apple-system, sans-serif; font-size: 13px; } main { max-width: 1120px; margin: auto; } h1 { margin: 0 0 6px; font-size: 26px; letter-spacing: -.5px; } h2 { margin: 0 0 12px; font-size: 16px; } p { line-height: 1.5; } .subtitle { margin: 0 0 18px; color: #586a7f; } .summaries, .charts { display: grid; gap: 16px; margin-bottom: 16px; } .summaries { grid-template-columns: repeat(3, minmax(0, 1fr)); } .charts { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; } section { background: white; padding: 16px; border: 1px solid #dbe3ec; border-radius: 12px; } table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; } th, td { text-align: left; padding: 5px 9px; border-bottom: 1px solid #e8edf3; } th { color: #53677c; font-size: 12px; background: #f5f8fc; } td:last-child, th:last-child { text-align: right; } tbody tr:last-child td { border-bottom: 0; } svg { display: block; width: 100%; height: auto; overflow: visible; } svg text { font: 11px system-ui, sans-serif; fill: #40546b; } svg .axis-title { font-size: 12px; font-weight: 600; } .gridline { stroke: #e5ebf2; stroke-width: 1; } .axis { fill: none; stroke: #8b9bad; stroke-width: 1; } .caption { margin: 8px 0 0; color: #586a7f; font-size: 12px; } @media (max-width: 760px) { body { padding: 12px; } .summaries, .charts { grid-template-columns: 1fr; } } """ parts = [ '', '', 'Boston and Titanic analysis', f'
', '

Boston Housing & Titanic

', f'

Reproducible data cleaning and group analysis · Boston: {len(clean)} retained / {len(boston)} rows · Titanic: {len(titanic)} rows

', '

Boston · IQR screening

', table('iqr-summary', ['Metric', 'Value'], [('Q1', f'{q1:.3f}'), ('Q3', f'{q3:.3f}'), ('lower', f'{low:.3f}'), ('upper', f'{high:.3f}'), ('outliers', str(len(outliers)))]), '

Top correlations with medv

', table('correlations', ['Feature', 'Pearson r'], [(name, f'{correlations[name]:.5f}') for name in top]), '

Pearson coefficients on the original Boston rows; ranked by absolute value.

', '

Mean medv by room group

', table('room-means', ['rm_rounded', 'Mean medv'], [(room, f'{mean:.3f}') for room, mean in sorted(means.items())]), '

Boston · rooms and home value

', scatter_chart(clean), f'

Blue: all {len(clean)} cleaned observations. Red: ordinary least-squares trend. Both axes use linear scales.

', '

Titanic · survival by passenger group

', survival_chart(rates), table('survival-rates', ['Sex', 'Class', 'Survival rate'], [(sex, category, f'{rate:.2%}') for (sex, category), rate in sorted(rates.items())]), '
', ] with open("report.html", "w", encoding="utf-8") as handle: handle.write("".join(parts))