Download task_024/solution/code/solve.py from Lego-X/UXInteract: direct link, hf CLI and curl.
- Browser
- Download file 4.07 kB
-
https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_024/solution/code/solve.py
- Command line
-
hf download hf://datasets/Lego-X/UXInteract/task_024/solution/code/solve.py
-
curl -L -o solve.py https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_024/solution/code/solve.py
4.07 kB
| import csv | |
| from collections import defaultdict | |
| from html import escape | |
| from statistics import median | |
| rows = list(csv.DictReader(open('titanic.csv', encoding='utf-8-sig'))) | |
| print(f'[1/4] loaded {len(rows)} Titanic records', flush=True) | |
| ages = [float(r['age']) for r in rows if r.get('age')] | |
| median_age = median(ages) if ages else 30 | |
| for r in rows: | |
| r['age'] = r.get('age') or str(median_age) | |
| r['deck'] = r.get('deck') or 'Unknown' | |
| r['embarked'] = r.get('embarked') or 'S' | |
| r['class'] = r.get('class') or r.get('pclass', '') | |
| sibsp = int(float(r.get('sibsp') or 0)) | |
| parch = int(float(r.get('parch') or 0)) | |
| r['is_alone'] = 'true' if sibsp + parch == 0 else 'false' | |
| # bucket age into an ordered category column (pandas-style astype('category')) | |
| age_val = float(r['age']) | |
| r['age_category'] = 'child' if age_val < 18 else ('senior' if age_val >= 60 else 'adult') | |
| print('[2/4] filled age/deck and derived is_alone', flush=True) | |
| # encode categorical columns into integer category codes (equivalent to | |
| # df[col].astype('category').cat.codes) for downstream modelling | |
| category_cols = ['sex', 'embarked', 'class', 'deck', 'age_category'] | |
| for col in category_cols: | |
| levels = sorted({(r.get(col) or '') for r in rows}) | |
| codes = {level: idx for idx, level in enumerate(levels)} | |
| for r in rows: | |
| r[col + '_code'] = str(codes[r.get(col) or '']) | |
| print('[3/4] encoded embarked/class categorical values', flush=True) | |
| extra = ['age', 'deck', 'embarked', 'class', 'is_alone', 'age_category'] + [c + '_code' for c in category_cols] | |
| fields = list(dict.fromkeys(list(rows[0].keys()) + extra)) | |
| with open('titanic_clean.csv', 'w', newline='', encoding='utf-8') as f: | |
| writer = csv.DictWriter(f, fieldnames=fields) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| groups = defaultdict(lambda: [0, 0]) | |
| for row in rows: | |
| survived = str(row.get('survived', '')).strip().lower() in {'1', 'true'} | |
| for field in ('sex', 'class'): | |
| counts = groups[(field, row[field])] | |
| counts[0] += int(survived) | |
| counts[1] += 1 | |
| table_rows = [] | |
| bars = [] | |
| for index, ((field, category), (survived, total)) in enumerate(sorted(groups.items())): | |
| rate = survived / total | |
| safe_field, safe_category = escape(field), escape(category) | |
| table_rows.append( | |
| f'<tr data-group="{safe_field}" data-category="{safe_category}" ' | |
| f'data-survived="{survived}" data-total="{total}" data-rate="{rate:.6f}">' | |
| f'<td>{safe_field}</td><td>{safe_category}</td><td>{survived}</td>' | |
| f'<td>{total}</td><td>{rate:.1%}</td></tr>' | |
| ) | |
| y = 16 + index * 38 | |
| bars.append( | |
| f'<text x="4" y="{y + 18}">{safe_field}: {safe_category}</text>' | |
| f'<rect data-group="{safe_field}" data-category="{safe_category}" ' | |
| f'data-rate="{rate:.6f}" x="170" y="{y}" width="{rate * 400:.2f}" ' | |
| f'height="24" fill="{"#267746" if field == "sex" else "#2563a6"}"/>' | |
| ) | |
| height = 32 + len(groups) * 38 | |
| report = ( | |
| '<!doctype html><html lang="en"><meta charset="utf-8"><title>Titanic survival analysis</title>' | |
| '<style>body{font:16px system-ui,sans-serif;max-width:900px;margin:2rem auto;padding:0 1rem}' | |
| 'table{border-collapse:collapse;width:100%;margin:1rem 0}th,td{border:1px solid #ccd6dd;padding:.5rem;text-align:left}' | |
| 'svg{max-width:100%;height:auto;border:1px solid #ccd6dd}</style>' | |
| '<main><h1>Titanic survival analysis</h1>' | |
| f'<p>Cleaned {len(rows)} records. Missing ages use the observed median; missing deck is Unknown.</p>' | |
| '<h2>Survival rates by sex and class</h2><table id="survival-rates">' | |
| '<thead><tr><th>Group</th><th>Category</th><th>Survived</th><th>Total</th><th>Rate</th></tr></thead>' | |
| '<tbody>' + ''.join(table_rows) + '</tbody></table>' | |
| f'<svg id="survival-chart" role="img" aria-label="Survival rate bar chart" viewBox="0 0 600 {height}">' | |
| + ''.join(bars) + '</svg></main></html>' | |
| ) | |
| with open('report.html', 'w', encoding='utf-8') as handle: | |
| handle.write(report) | |
| print('[4/4] wrote titanic_clean.csv and report.html', flush=True) | |