Download task_025/solution/code/solve.py from Lego-X/UXInteract: direct link, hf CLI and curl.
- Browser
- Download file 5.98 kB
-
https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_025/solution/code/solve.py
- Command line
-
hf download hf://datasets/Lego-X/UXInteract/task_025/solution/code/solve.py
-
curl -L -o solve.py https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_025/solution/code/solve.py
5.98 kB
| import csv, json, statistics | |
| from html import escape | |
| rows = list(csv.DictReader(open('gapminderDataFiveYear.csv', encoding='utf-8-sig'))) | |
| rows2007 = [r for r in rows if str(r.get('year')) == '2007'] | |
| for row in rows2007: | |
| row['gdp_per_capita'] = round(float(row['gdpTotal']) / float(row['pop']), 6) | |
| with open('gapminder_2007.json', 'w', encoding='utf-8') as f: | |
| json.dump(rows2007, f, ensure_ascii=False, indent=2) | |
| gdp = [float(r['gdp_per_capita']) for r in rows2007] | |
| life = [float(r.get('lifeExp') or r.get('life') or 0) for r in rows2007] | |
| # Aggregate 2007 metrics by continent: mean life expectancy and mean GDP per | |
| # capita for each continent, sorted by life expectancy. | |
| by_continent = {} | |
| for r in rows2007: | |
| continent = r.get('continent') or 'Unknown' | |
| entry = by_continent.setdefault(continent, {'life': [], 'gdp': [], 'pop': []}) | |
| entry['life'].append(float(r.get('lifeExp') or r.get('life') or 0)) | |
| entry['gdp'].append(float(r['gdp_per_capita'])) | |
| entry['pop'].append(float(r.get('pop') or 0)) | |
| continent_stats = [] | |
| for continent, vals in by_continent.items(): | |
| continent_stats.append({ | |
| 'continent': continent, | |
| 'countries': len(vals['life']), | |
| 'mean_lifeExp': round(statistics.mean(vals['life']), 2) if vals['life'] else 0, | |
| 'mean_gdpPercap': round(statistics.mean(vals['gdp']), 2) if vals['gdp'] else 0, | |
| 'mean_population': round(statistics.mean(vals['pop']), 2) if vals['pop'] else 0, | |
| }) | |
| continent_stats.sort(key=lambda c: c['mean_lifeExp'], reverse=True) | |
| by_country = {} | |
| for row in rows: | |
| by_country.setdefault(row['country'], {})[row['year']] = float(row['pop']) | |
| growth = {country: years['2007'] - years['1952'] for country, years in by_country.items() | |
| if '1952' in years and '2007' in years} | |
| fastest_growth_country = max(growth, key=growth.get) | |
| with open('continent_2007_stats.csv', 'w', newline='', encoding='utf-8') as f: | |
| writer = csv.DictWriter(f, fieldnames=['continent', 'countries', 'mean_lifeExp', 'mean_gdpPercap', 'mean_population']) | |
| writer.writeheader() | |
| writer.writerows(continent_stats) | |
| palette = {'Asia': '#2563eb', 'Americas': '#db2777', 'Europe': '#15803d'} | |
| min_gdp, max_gdp = min(gdp), max(gdp) | |
| min_life, max_life = min(life), max(life) | |
| points = [] | |
| axis_labels = ( | |
| '<path d="M65 50 V280 H565" fill="none" stroke="#64748b"/>' | |
| f'<text x="65" y="298" font-size="10">{min_gdp:.0f}</text>' | |
| f'<text x="565" y="298" text-anchor="end" font-size="10">{max_gdp:.0f}</text>' | |
| '<text id="gdp-axis-label" x="315" y="319" text-anchor="middle" font-size="12">GDP per capita</text>' | |
| f'<text x="57" y="280" text-anchor="end" font-size="10">{min_life:.1f}</text>' | |
| f'<text x="57" y="64" text-anchor="end" font-size="10">{max_life:.1f}</text>' | |
| '<text id="life-axis-label" x="65" y="27" font-size="12">Life expectancy (years)</text>' | |
| ) | |
| legend = '<div id="continent-legend">' + ' · '.join( | |
| f'<span data-continent="{escape(continent)}" style="color:{color}">● {escape(continent)}</span>' | |
| for continent, color in palette.items()) + '</div>' | |
| for row in rows2007: | |
| country = escape(row['country']) | |
| continent = escape(row['continent']) | |
| per_capita = float(row['gdp_per_capita']) | |
| life_exp = float(row['lifeExp']) | |
| x = 65 + (per_capita - min_gdp) / max(max_gdp - min_gdp, 1) * 500 | |
| y = 280 - (life_exp - min_life) / max(max_life - min_life, 1) * 220 | |
| points.append( | |
| f'<circle data-country="{country}" data-continent="{continent}" ' | |
| f'data-gdp="{per_capita:.6f}" data-life="{life_exp:.6f}" ' | |
| f'cx="{x:.2f}" cy="{y:.2f}" r="6" fill="{palette[row["continent"]]}">' | |
| f'<title>{country}: GDP/person {per_capita:.1f}, life {life_exp:.1f}</title></circle>' | |
| ) | |
| rows_html = [] | |
| bars = [] | |
| max_population = max(item['mean_population'] for item in continent_stats) | |
| for index, item in enumerate(continent_stats): | |
| continent = escape(item['continent']) | |
| mean_population = item['mean_population'] | |
| rows_html.append( | |
| f'<tr data-continent="{continent}" data-mean-pop="{mean_population:.2f}">' | |
| f'<td>{continent}</td><td>{item["countries"]}</td><td>{mean_population:,.2f}</td></tr>' | |
| ) | |
| y = 15 + index * 42 | |
| bars.append( | |
| f'<text x="5" y="{y+19}">{continent}</text>' | |
| f'<rect data-continent="{continent}" data-mean-pop="{mean_population:.2f}" ' | |
| f'x="105" y="{y}" width="{mean_population / max_population * 450:.2f}" ' | |
| f'height="27" fill="{palette[item["continent"]]}"/>' | |
| ) | |
| report = ( | |
| '<!doctype html><html lang="en"><meta charset="utf-8"><title>Gapminder 2007 report</title>' | |
| '<style>body{font:16px system-ui,sans-serif;max-width:950px;margin:2rem auto;padding:0 1rem}' | |
| 'table{border-collapse:collapse;margin:1rem 0}th,td{border:1px solid #ccd6dd;padding:.5rem}' | |
| 'svg{max-width:100%;height:auto;border:1px solid #ccd6dd}</style><main>' | |
| '<h1>2007 GDP per capita and life expectancy</h1>' | |
| f'<p id="fastest-growth" data-country="{escape(fastest_growth_country)}" ' | |
| f'data-absolute-growth="{growth[fastest_growth_country]:.0f}">' | |
| f'Fastest absolute population growth (1952–2007): {escape(fastest_growth_country)}, ' | |
| f'+{growth[fastest_growth_country]:,.0f} people.</p>' | |
| '<h2>GDP per capita vs life expectancy by continent</h2>' | |
| '<svg id="gdp-life-scatter" role="img" aria-label="GDP per capita and life expectancy scatter plot" viewBox="0 0 600 330">' | |
| + axis_labels + ''.join(points) + '</svg>' + legend + | |
| '<h2>Mean population by continent, 2007</h2>' | |
| '<table id="continent-population"><thead><tr><th>Continent</th><th>Countries</th><th>Mean population</th></tr></thead><tbody>' | |
| + ''.join(rows_html) + '</tbody></table>' | |
| f'<svg id="continent-population-bars" role="img" aria-label="Mean population bar chart" viewBox="0 0 600 {30 + 42 * len(bars)}">' | |
| + ''.join(bars) + '</svg></main></html>' | |
| ) | |
| with open('report.html', 'w', encoding='utf-8') as handle: | |
| handle.write(report) | |