Add files via upload

This commit is contained in:
Peter Norvig 2020-10-06 23:12:10 -07:00 committed by GitHub
parent bd61b676b2
commit 730af5fde5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 517 additions and 182 deletions

File diff suppressed because one or more lines are too long

View File

@ -4,7 +4,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"<div align=\"right\"><i>Peter Norvig<br>12 August 2019</i></div>\n",
"<div align=\"right\"><i>Peter Norvig<br>12 August 2019<br>Update Oct 2020</i></div>\n",
"\n",
"# Data and Code for [Tracking Trump: Electoral Votes Edition](Electoral%20Votes.ipynb)\n",
"\n",
@ -12,7 +12,7 @@
" gives state-by-state, month-by-month presidential approval poll data. Within the web page there is some Javascript from which\n",
" we can extract the data we need. It looks like this:\n",
"\n",
" var mc_state_trend = [[\"Demographic\",\"Jan-17\",\"\",\"Feb-17\",\"\", ...]\n",
" var mc_state_trend = [[\"Demographic\",\"January '17\",\"\",\"February '17\",\"\", ...]\n",
" [\"Alabama\",\"62\",\"26\",\"65\",\"29\", ...], \n",
" ... ]\n",
" \n",
@ -28,7 +28,7 @@
"metadata": {},
"outputs": [],
"source": [
"! curl -s -o evs.html https://morningconsult.com/tracking-trump-2/"
"! [ -e evs.html ] || curl -s -o evs.html https://morningconsult.com/tracking-trump-2/"
]
},
{
@ -128,13 +128,17 @@
" \"Read data from the file and return tuple: (list of `State`s, list of dates).\"\n",
" text = re.findall(r'\\[\\[.*?\\]\\]', open(filename).read())[0]\n",
" header, *table = ast.literal_eval(text)\n",
" dates = header[1::2]\n",
" dates = [date32(d) for d in header[1::2]]\n",
" states = [State(name, *state_data[name],\n",
" approvals=dict(zip(dates, map(int, numbers[0::2]))),\n",
" disapprovals=dict(zip(dates, map(int, numbers[1::2]))))\n",
" for (name, *numbers) in table]\n",
" return states, dates\n",
"\n",
"def date32(date) -> str: \n",
" \"\"\"Convert a date to 3-2 format: date32(\"June '17\") => 'Jun-17'.\"\"\"\n",
" return date[:3] + '-' + date[-2:]\n",
"\n",
"states, dates = parse_page('evs.html')\n",
"now = dates[-1]\n",
"\n",
@ -178,7 +182,7 @@
"\n",
"def grid(dates, xlab, ylab): \n",
" plt.minorticks_on(); plt.grid(which='minor', axis='y', ls=':', alpha=0.7)\n",
" plt.xticks(range(len(dates)), dates, rotation=90)\n",
" plt.xticks(range(len(dates)), dates, rotation=90, fontfamily='monospace')\n",
" plt.xlabel(xlab); plt.ylabel(ylab); plt.legend()"
]
},
@ -198,7 +202,7 @@
" plt.plot(range(N), [270] * N, color='darkorange', label=\"270 EVs\", lw=2)\n",
" plt.errorbar(range(N), [EV(states, date) for date in dates], fmt='D-',\n",
" yerr=err, ecolor='grey', capsize=7, label='Trump EVs ±3% swing', lw=2)\n",
" grid(dates, 'Date', 'Electoral Vptes')\n",
" grid(dates, 'Date', 'Electoral Votes')\n",
" #labels('Date', 'Electoral Votes')"
]
},
@ -271,6 +275,40 @@
" yield f'|{swing_name(s)}|{s.lean:+d}|{s.ev}|{\"|\".join(fields)}|'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Show how to make all Electoral Vote totals:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"def all_totals(states) -> dict:\n",
" \"\"\"Return a dict of {ev_total: [state, ...]}\"\"\"\n",
" totals = {0: []}\n",
" for s in sorted(states, key=lambda s: s.ev):\n",
" new = {}\n",
" for t in totals:\n",
" new[t + s.ev] = shorter(totals.get(t + s.ev), totals[t] + [s.name])\n",
" totals = {**totals, **new}\n",
" return totals\n",
" \n",
"def shorter(A, B):\n",
" \"\"\"Return the sequence that is shorter, but always return B if A is None.\"\"\"\n",
" return B if A is None or len(A) > len(B) else A\n",
"\n",
"def show_totals():\n",
" districts = [State('Maine-1', 1, 0, 0, 0), State('Maine-2', 1, 0, 0, 0)]\n",
" totals = all_totals(states + districts)\n",
" for i in range(270):\n",
" print(f\"{i:3} [{' + '.join(totals[i])}]\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
@ -280,7 +318,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
@ -306,7 +344,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
"version": "3.7.6"
}
},
"nbformat": 4,