{
 "metadata":{},
 "nbformat":4,
 "nbformat_minor":4,
 "cells":[
  {
   "cell_type":"markdown",
   "metadata":{
    "editable":true
   },
   "source":[
    "<!-- jupyter-book 04_01_testdoc.ipynb -->\n",
    "# Problem: Flip a Coin\n",
    "\n",
    "<div id=\"demo:ex:1\"></div>\n",
    "files = flip_coin.py, flip_coin.pdf\n",
    "solutions = mysol.txt, mysol_flip_coin.py\n",
    "keywords = random numbers; Monte Carlo simulation; ipynb\n",
    "\n",
    "<!-- Torture tests -->\n",
    "file=myfile_should_be_a_part_of_the_text\n",
    "solutions = mysol.txt, mysol_flip_coin.py, yet_another.file\n",
    "\n",
    "!bsubex\n",
    "Make a program that simulates flipping a coin $N$ times.\n",
    "Print out \"tail\" or \"head\" for each flip and\n",
    "let the program count the number of heads.\n",
    "\n",
    "**Hint.**\n",
    "\n",
    "Use `r = random.random()` and define head as `r <= 0.5`.\n",
    "\n",
    "\n",
    "\n",
    "**Hint.**\n",
    "\n",
    "Draw an integer among $\\{1,2\\}$ with\n",
    "`r = random.randint(1,2)` and define head when `r` is 1.\n",
    "\n",
    "\n",
    "\n",
    "!bans\n",
    "If the `random.random()` function returns a number $<1/2$, let it be\n",
    "head, otherwise tail. Repeat this $N$ number of times.\n",
    "!eans\n",
    "\n",
    "!bsol"
   ]
  },
  {
   "cell_type":"code",
   "execution_count":9,
   "metadata":{
    "collapsed":false,
    "editable":true
   },
   "outputs":[],
   "source":[
    "import sys, random\n",
    "N = int(sys.argv[1])\n",
    "heads = 0\n",
    "for i in range(N):\n",
    "    r = random.random()\n",
    "    if r <= 0.5:\n",
    "        heads += 1\n",
    "print('Flipping a coin %d times gave %d heads' % (N, heads))"
   ]
  },
  {
   "cell_type":"markdown",
   "metadata":{
    "editable":true
   },
   "source":[
    "!esol\n",
    "!esubex\n",
    "\n",
    "!bsubex\n",
    "Vectorize the code in a) using boolean indexing.\n",
    "!esubex\n",
    "\n",
    "Vectorized code can be written in many ways.\n",
    "Sometimes the code is less intuitive, sometimes not.\n",
    "At least there is not much to find in the section [Section 1](sec1.html#sec1).\n",
    "\n",
    "!bsubex\n",
    "Vectorize the code in a) using `numpy.sum`.\n",
    "\n",
    "!bans\n",
    "`np.sum(np.where(r <= 0.5, 1, 0))` or `np.sum(r <= 0.5)`.\n",
    "!eans\n",
    "!esubex\n",
    "\n",
    "In this latter subexercise, we have an\n",
    "example where the code is easy to read.\n",
    "\n",
    "**Remarks.**\n",
    "\n",
    "These are the exercise remarks, appearing at the very end.\n",
    "\n",
    "\n",
    "\n",
    "### My remarks\n",
    "\n",
    "Remarks with such a subsubsection is treated as more text\n",
    "after the last subexercise. Test a list too:\n",
    "\n",
    "1. Mark 1.\n",
    "\n",
    "2. Mark 2."
   ]
  }
 ]
}