{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <p style=\"text-align: right;\"> &#9989; Put your name here.</p>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Homework Assignment #1 (Individual)\n",
    "## Debugging Practice, Electoral College, and Writing Python Scripts\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Goals for this homework assignment\n",
    "By the end of this assignment, you should be able to:\n",
    "* Debug Python code.\n",
    "* Get more experience with Pandas using excel spread sheets.\n",
    "* Make plots of your model using <code>matplotlib</code>.\n",
    "* Practice writing and executing a Python script.\n",
    "\n",
    "### Assignment instructions\n",
    "\n",
    "Work through the following assignment, making sure to follow all of the directions and answer all of the questions.\n",
    "\n",
    "There are **25 points** possible on this assignment. Point values for each part are included in the section headers.\n",
    "\n",
    "**This assignment is due at 11:59 pm on Friday, September 25th.** It should be uploaded into the \"Homework Assignments\" submission folder for Homework #1 in your D2L webpage.  Submission instructions can be found at the end of the notebook."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Part 1: Debugging code: understanding error messages (3 points)\n",
    "\n",
    "For this part of this assignment, you're going to presented with a variety of code bugs and your job is to fix them."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Fixing errors\n",
    "\n",
    "<p style=\"text-align: left;\"> &#9989; To Do</p> \n",
    "For each piece of code, rewrite it in the cell below and fix the error so that the code runs. If it is a runtime error, fix it with a message to avoid running the incorrect code. In the code you write, provide a comment as to what was wrong."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "for i in range(10)\n",
    "    print(\"The value of i is {}\".format(i))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your answer here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cnt = 10\n",
    "the_sum = 0\n",
    "for i in range(cnt):\n",
    "    if i%2 == 0:\n",
    "    the_sum += i\n",
    "print(\"The sum of the even number from {} to {} is {}\".format(0,cnt,the_sum))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your answer here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_fraction(numerator, denominator):\n",
    "    fraction = numerator/denominator\n",
    "    print(\"The value of the fraction is {}\".format(fraction))\n",
    "\n",
    "compute_fraction(25,5)\n",
    "compute_fraction(5,25)\n",
    "compute_fraction(5, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your answer here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import random\n",
    "\n",
    "cnt = 10\n",
    "n = np.arange(cnt)\n",
    "for i in range(cnt):\n",
    "    n[i] = random.randint(100,1000)\n",
    "print(i)\n",
    "print(\"The value of the 10th element is {}\".format(n[cnt]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your answer here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cnt = 100\n",
    "even = [ i for i in range(cnt) if i%2 ]\n",
    "\n",
    "print(\"The largest even number in the range {} to {} is {}\".format(0,cnt,max(even)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your answer here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "spanish = { \n",
    "'hello':'hola',\n",
    "'yes':'si'\n",
    "'one':'uno'\n",
    "}\n",
    "\n",
    "print(\"'Hello' in spanish is {}\".format(spanish['Hello']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your answer here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Part 2: Calculating Electors (11 points)\n",
    "\n",
    "Before we go too far, let's pull in all the imports we need. If we have to, we can come back here and do it again in one cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import datetime"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The 2020 lections are coming up, good to understand how the electoral college works. The <a href=\"https://en.wikipedia.org/wiki/United_States_Electoral_College\"> Electoral College </a> is provided by the U.S. constitution as the method of electing the president. In total 538 electors are divided amoung the 50 states and the District of Columbia. This total comes from:\n",
    "\n",
    "* 435 U.S. House representatives. That number is fixed <a href=\"https://en.wikipedia.org/wiki/Apportionment_Act_of_1911\"> by law </a>\n",
    "* 100 U.S. Senators\n",
    "* presently 3 representatives to the District of Columbia as provided by the <a\n",
    " href=\"https://en.wikipedia.org/wiki/Twenty-third_Amendment_to_the_United_States_Constitution\"> Twenty-third Amendment </a>\n",
    " \n",
    "The number of U.S. House representatives are determined by population based on the <a href=\"https://en.wikipedia.org/wiki/United_States_Census\"> U.S. Census </a> that is conducted every 10 years (and is presently being run in 2020).\n",
    "\n",
    "We are going to look at some possibilities based on available data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.1 U.S. Population and Region Data (4 points)\n",
    "\n",
    "Wikipedia is a good repository for U.S. data.  We are going to \"scrape\" some of that data from wikipedia using `pandas` and the `read_html` function. Look it up, figure out how it works\n",
    "\n",
    "- read in from \"https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States_by_population#Summary_of_population_by_region\". You can look at it to see the tables. We want the table that contains the 2019/2010/2000 population and Geographic Region with the heading \"Summary of Population by Region\"\n",
    "- reduce the table to 50 rows, one for each state, and 5 columns: state, 2019 pop, 2010 pop, 2000 pop, region\n",
    "- print the whole data frame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.2 Apportionment of House Representatives (7 points)\n",
    "The algorithm for apportionment of the number of house representatives is called <a href=\"https://en.wikipedia.org/wiki/United_States_congressional_apportionment#The_method_of_equal_proportions\"> Method of Equal Proportions </a>. Write a function `apportion` that takes the following argument:\n",
    "- a pandas Series of the population of each state\n",
    "- the number of seats being apportioned\n",
    "It returns:\n",
    "- a pandas Series of the number of representatives apportioned to each state\n",
    "\n",
    "We are only dealing with the 435 members of the house. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your code here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "ser = df[\"2010\"]\n",
    "print(ser.head())\n",
    "electors = apportion(ser, 435)\n",
    "electors = electors + [2]*50\n",
    "print(electors.sort_index())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3 Simulate the Election (11 points)\n",
    "\n",
    "## 3.1 Read the Data (2 point)\n",
    "\n",
    "The website <a href=\"https://fivethirtyeight.com/\"> 538 </a> (Hey, you know where the name comes from now) records current polls based on an algorithm they have devised. They make their <a href=\"https://data.fivethirtyeight.com\"> data available </a> for us to play around with. Yeah for them!\n",
    "\n",
    "Do the following:\n",
    "- download the data labeled \"2020 Election Forecast\"\n",
    "- unzip the file\n",
    "- find the file for the state (\"state_toplines\")\n",
    "- read it in as a DataFrame\n",
    "- show the `.head()` of that"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.2 Pare down the data (3 points)\n",
    "\n",
    "We are interested in only 4 columns. We want the State and the two `voteshare` percentages (incumbent vs challenger) which represents the odds of winning for that state. We also want the `modeldate`. We want to filter out all entries except for one modeldate (of your choice). Take the data from above and pare it down to that."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your code"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Maine, Nebraska and the District of Columbia\n",
    "\n",
    "It turns out that all the states do a \"winner take all\" approach to their electoral candidates. Whichever candidate receives the majority of votes of a state gets all the electoral votes from that state. Except for two states: Maine (ME) and Nebraska (NE). Those two states use the following system:\n",
    "\n",
    "Each congressional district result gets 1 electoral vote and then the entire state result contributes two electoral votes. Thus:\n",
    "\n",
    "- ME-1 and ME-2 are worth one electoral vote each and the overall Maine result is worth two electoral votes (total of 4)\n",
    "- Similarly, NE-1, NE-2 and NE-3 are each worth 1 electoral vote and Nebraska overall is worth two electoral votes (total of 5)\n",
    "\n",
    "The District of Columbia is special and cannot have more electoral votes than the smallest state number, meaning DC has a total of 3 electoral votes.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.3. Simulate an Election (6 points)\n",
    "\n",
    "We now have all we need to simulate a presidential election given the population of the United States. Let's do the following:\n",
    "\n",
    "- pick a particular population of US states from the wikipedia web scrape (we grabbed three: 2000, 2010, 2019)\n",
    "- generate the electors for those states based on that population\n",
    "- Pick a particular date from the 538 data for each state's presidential percentages. Classify them as follows:\n",
    "   - 7 categories: for each candidate have \"strong\", \"likely\" and \"weak\"\n",
    "      - if > 10% difference, then \"strong\"\n",
    "      - if 10%-5% difference then \"likely\"\n",
    "      - if 5%-2% difference \"weak\"\n",
    "   - 7th category is \"tossup\" if difference is less than 2% (inside the margin of error)\n",
    "- make a histogram/barchart of the totals in each of the 7 categories and say which candidate would win (would receive 270 or more electoral votes)\n",
    "    - ignore tossup votes in determining a winner (but still graph them)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### Assignment wrap-up\n",
    "\n",
    "Please fill out the form that appears when you run the code below.  **You must completely fill this out in order to receive credit for the assignment!**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import HTML\n",
    "HTML(\n",
    "\"\"\"\n",
    "<iframe \n",
    "\tsrc=\"https://docs.google.com/forms/d/e/1FAIpQLSfKXN0F9vdyJOIQkfeMhQ2X-fdzKeXJ_lFX_M8T9kQJd4ttBg/viewform?usp=sf_link\" \n",
    "\twidth=\"800px\" \n",
    "\theight=\"600px\" \n",
    "\tframeborder=\"0\" \n",
    "\tmarginheight=\"0\" \n",
    "\tmarginwidth=\"0\">\n",
    "\tLoading...\n",
    "</iframe>\n",
    "\"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Congratulations, you're done!\n",
    "\n",
    "Submit this assignment by uploading it to the course Desire2Learn web page.  Go to the \"Homework Assignments\" folder, find the dropbox link for Homework #1, and upload it there."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&#169; Copyright Michigan State University Board of Trustees"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
