{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "<div style=\"float:right\"><i>Peter Norvig<br>5 January 2016</i></div>\n",
    "\n",
    "# Countdown to 2016\n",
    "\n",
    "Alex Bellos [posed](http://www.theguardian.com/science/2016/jan/04/can-you-solve-it-complete-the-equation-10-9-8-7-6-5-4-3-2-1-2016) this New Year's puzzle:\n",
    "\n",
    "\n",
    "> Fill in the blanks so that this equation makes arithmetical sense:\n",
    "\n",
    "> 10 &square; 9 &square; 8 &square; 7 &square; 6 &square; 5 &square; 4 &square; 3 &square; 2 &square; 1 = 2016\n",
    "\n",
    "> You are allowed to use *only* the four basic arithmetical operations: +, -, &times;, ÷. But brackets (parentheses) can be used wherever needed. So, for example, the solution could begin\n",
    "\n",
    "> (10 - 9) &times; (8 ...\n",
    "\n",
    "> or\n",
    "\n",
    "> 10 + (9 &times; 8) ...\n",
    "\n",
    "Let's see if we can solve this puzzle, and some of the related ones from Alex's [first](http://www.theguardian.com/science/2016/jan/04/can-you-solve-it-complete-the-equation-10-9-8-7-6-5-4-3-2-1-2016) and [second](http://www.theguardian.com/science/2016/jan/04/did-you-solve-it-complete-the-equation-10-9-8-7-6-5-4-3-2-1-2016) post.  We'll start with a  simpler version of the puzzle."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Four Operators, No Brackets\n",
    "\n",
    "Suppose for the moment we are not allowed to use brackets.  Then there are nine blanks,  each of which can be filled by one of four operators, so the total number of possible expressions is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "262144"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "4 ** 9"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "That's small enough that we can just enumerate all the expressions and see if any evaluates to 2016.\n",
    "We will generate each expression as a string and then evaluate it with `eval`. But we need to catch errors such as dividing by zero, so we'll define a wrapper function, `evaluate`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from __future__ import division\n",
    "\n",
    "def evaluate(exp):\n",
    "    \"eval exp, or return None if there is an arithmetic error.\"\n",
    "    try:\n",
    "        return eval(exp)\n",
    "    except ArithmeticError:\n",
    "        return None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We'll try each of the four operators in each of the nine blanks, evaluate each resulting expression, and collect the ones that evaluate to 2016:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def solve_no_brackets(ops=('+', '-', '*', '/')):\n",
    "    \"All solutions to the countdown puzzle (with no brackets).\"\n",
    "    exps = ('10'+a+'9'+b+'8'+c+'7'+d+'6'+e+'5'+f+'4'+g+'3'+h+'2'+i+'1'\n",
    "            for a in ops    for b in ops    for c in ops \n",
    "            for d in ops    for e in ops    for f in ops \n",
    "            for g in ops    for h in ops    for i in ops)\n",
    "    return [exp for exp in exps if evaluate(exp) == 2016]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "solve_no_brackets()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Too bad; we did all that work and didn't find a solution. What years *can* we find solutions for? Let's modify `solve_no_brackets` to take a collection of target years, and return a dict of the form `{year: \"expression\"}` for each expression that evaluates to one of the target years:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def solve_no_brackets(targets, ops=('+', '-', '*', '/')):\n",
    "    \"Solutions to the no-bracket countdown puzzle matching one of targets.\"\n",
    "    exps = ('10'+a+'9'+b+'8'+c+'7'+d+'6'+e+'5'+f+'4'+g+'3'+h+'2'+i+'1'\n",
    "            for a in ops    for b in ops    for c in ops \n",
    "            for d in ops    for e in ops    for f in ops \n",
    "            for g in ops    for h in ops    for i in ops)\n",
    "    return {int(evaluate(exp)): exp\n",
    "            for exp in exps if evaluate(exp) in targets}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Let's try it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 12.7 s, sys: 265 ms, total: 13 s\n",
      "Wall time: 18.9 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{1979: '10*9*8+7*6*5*4*3/2-1',\n",
       " 1980: '10*9*8+7*6*5*4*3/2/1',\n",
       " 1981: '10*9*8+7*6*5*4*3/2+1',\n",
       " 2013: '10*9*8*7/6/5*4*3-2-1',\n",
       " 2014: '10*9*8*7/6/5*4*3-2/1',\n",
       " 2015: '10*9*8*7/6/5*4*3-2+1',\n",
       " 2017: '10*9*8*7/6/5*4*3+2-1',\n",
       " 2018: '10*9*8*7/6/5*4*3+2/1',\n",
       " 2019: '10*9*8*7/6/5*4*3+2+1'}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time solve_no_brackets(range(1900, 2100))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Interesting: in the 20th and 21st centuries, there are only two \"golden eras\" where the countdown equation works: the three year period centered on 1980, and the seven year period that is centered on 2016, but omits 2016. Note it takes about half a minute to do the computation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Four Operators, With Brackets\n",
    "\n",
    "Now let's return to the original puzzle, with the brackets. How many ways are there of bracketing an expression with 9 binary operators? I happen to remember that this is given by the [Catalan numbers](https://en.wikipedia.org/wiki/Catalan_number), and we can [look it up](http://www.wolframalpha.com/input/?i=9th+catalan+number) to find that there are 4862 diffferent bracketing. If we enumerated and evaluated all of them, 4862 times half a minute is [40 hours](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=4862+*+1%2F2+minute+in+hours). I'm impatient, so I'd like a faster approach. One possibility would be to switch to a faster compiled language like C++ or Go. But I'll concentrate on a better algorithm and stick with Python.\n",
    "\n",
    "I'll use the idea of [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming): break the problem down into simpler subparts, and compute an answer for each subpart, and store intermediate results in a table so we don't need to re-compute them when we need them again.\n",
    "\n",
    "How do we break the problem into parts? In general, any expression must consist of an operator with two operands (which might in turn be complex subexpressions). For example, a complete countdown expression might be of the form\n",
    "\n",
    "    (10 ... 8) + (7 ... 1)\n",
    "    \n",
    "where `(10 ... 8)` means some expression that starts with 10 and ends with 8.  Of course we need not use `'+'` as the operator, and we need not split after the 8; we could use any of the four operators and split anywhere.  Let's start by defining `c10` as the tuple of integers forming the countdown from 10 to 1,  and the function `splits` to split a tuple in all ways: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "c10 = (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)\n",
    "\n",
    "def splits(items):\n",
    "    \"Split sequence of items into two non-empty parts, in all ways.\"\n",
    "    return [(items[:i], items[i:]) \n",
    "            for i in range(1, len(items))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[((10,), (9, 8, 7, 6, 5, 4, 3, 2, 1)),\n",
       " ((10, 9), (8, 7, 6, 5, 4, 3, 2, 1)),\n",
       " ((10, 9, 8), (7, 6, 5, 4, 3, 2, 1)),\n",
       " ((10, 9, 8, 7), (6, 5, 4, 3, 2, 1)),\n",
       " ((10, 9, 8, 7, 6), (5, 4, 3, 2, 1)),\n",
       " ((10, 9, 8, 7, 6, 5), (4, 3, 2, 1)),\n",
       " ((10, 9, 8, 7, 6, 5, 4), (3, 2, 1)),\n",
       " ((10, 9, 8, 7, 6, 5, 4, 3), (2, 1)),\n",
       " ((10, 9, 8, 7, 6, 5, 4, 3, 2), (1,))]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "splits(c10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Now what I would like to do is build up a table that says, for every subsequence of the numbers,  what are the expressions we can make with those numbers, and what do they evaluate to? We'll call the table `EXPS`. For example, with the subsequence `(10, 9, 8)`, we would have:\n",
    "\n",
    "    EXPS[(10, 9, 8)] = {\n",
    "      27: '((10+9)+8)',\n",
    "      8:  '((10-9)*8)', \n",
    "      -7: '(10-(9+8))', \n",
    "      ...}\n",
    "     \n",
    "We'll do the same for every other subsequence, for example:\n",
    "\n",
    "    EXPS[(7, 6, 5, 4, 3, 2, 1)] = {\n",
    "      1:   '((((7/((6/5)-4))+3)*2)*1)',\n",
    "      2:   '((((7/((6/5)-4))+3)*2)+1)',\n",
    "      3.5: '((((7/((6/5)-4))+3)+2)+1)',\n",
    "      4:   '((7-((6/5)*((4/3)+2)))+1)',\n",
    "      ...}\n",
    "     \n",
    "Once we have the tables for these two subsequences, we can put them together to get the table for the complete  `countdown(10)` by considering all ways of taking a value from the first table, then one of the four operators, then a value from the second table.  For example, taking the first entry from each table, and the operator `'+'`, we would have:\n",
    "\n",
    "    EXPS[(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)] = { \n",
    "      28: '(((10+9)+8)+((((7/((6/5)-4))+3)*2)*1))',\n",
    "      ...}\n",
    "\n",
    "\n",
    "I can implement `EXPS` as a defaultdict of dicts, and define `expressions(numbers)` to fill in `EXPS` entries for `numbers` and all sub-sequences of `numbers`.  Within `fill_tables`, note that `Lnums` and `Rnums` are sequences of numbers, such as `(10, 9, 8)` and `(7, 6)`. `L` and `R` are values, such as `27` and `1`. And `Lexp` and `Rexp` are strings, such as `\"((10+9)+8)\"` and `\"(7-6)\"`. Rather than catching division-by-zero errors, we just avoid the division when the denominator is 0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from collections import defaultdict, Counter\n",
    "import itertools\n",
    "\n",
    "EXPS = defaultdict(dict) # e.g., EXPS[(10, 9, 8)][27] == '((10+9)+8)'\n",
    "\n",
    "def expressions(numbers):\n",
    "    \"Fill EXPS table for numbers, and all sub-sequences of numbers. Return EXPS[numbers]\"\n",
    "    if numbers in EXPS: # Already did the work\n",
    "        pass\n",
    "    elif len(numbers) == 1: # Only one way to make an expression out of a single number\n",
    "        expr(numbers, numbers[0], str(numbers[0]))\n",
    "    else: # Split in all ways; fill tables for left and right; combine tables in all ways\n",
    "        for (Lnums, Rnums) in splits(numbers):\n",
    "            for (L, R) in itertools.product(expressions(Lnums), expressions(Rnums)):\n",
    "                Lexp, Rexp = '(' + EXPS[Lnums][L], EXPS[Rnums][R] + ')'\n",
    "                if R != 0: \n",
    "                    expr(numbers, L / R, Lexp + '/' + Rexp)\n",
    "                expr(numbers, L * R, Lexp + '*' + Rexp)\n",
    "                expr(numbers, L - R, Lexp + '-' + Rexp)\n",
    "                expr(numbers, L + R, Lexp + '+' + Rexp)\n",
    "    return EXPS[numbers]\n",
    "\n",
    "def expr(numbers, value, exp): \n",
    "    \"Record exp as an expression with the given value, covering the sequence of numbers.\"\n",
    "    EXPS[numbers][value] = exp"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Let's give it a try:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{-62: '(10-(9*8))',\n",
       " -7: '((10-9)-8)',\n",
       " -6.888888888888889: '((10/9)-8)',\n",
       " 0.125: '((10-9)/8)',\n",
       " 0.1388888888888889: '((10/9)/8)',\n",
       " 0.5882352941176471: '(10/(9+8))',\n",
       " 2.375: '((10+9)/8)',\n",
       " 8: '((10-9)*8)',\n",
       " 8.875: '(10-(9/8))',\n",
       " 8.88888888888889: '((10/9)*8)',\n",
       " 9: '((10-9)+8)',\n",
       " 9.11111111111111: '((10/9)+8)',\n",
       " 10.0: '(10*(9-8))',\n",
       " 11: '((10+9)-8)',\n",
       " 11.125: '(10+(9/8))',\n",
       " 11.25: '((10*9)/8)',\n",
       " 27: '((10+9)+8)',\n",
       " 82: '((10*9)-8)',\n",
       " 98: '((10*9)+8)',\n",
       " 152: '((10+9)*8)',\n",
       " 170: '(10*(9+8))',\n",
       " 720: '((10*9)*8)'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "expressions((10, 9, 8))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'((10+9)+8)'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "EXPS[(10, 9, 8)][27]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "That looks reasonable. Let's solve the whole puzzle.\n",
    "\n",
    "# Countdown to 2016: A Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1min, sys: 4 s, total: 1min 4s\n",
      "Wall time: 1min 55s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'(((((((10+((9*8)*7))-6)-5)*4)+3)+2)-1)'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time expressions(c10)[2016]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We have an answer! And in a lot less than 40 hours, thanks to dynamic programming! \n",
    "\n",
    "Removing unnecessry brackets, this equation is equivalent to:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2016"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(10 + 9 * 8 * 7 - 6 - 5) * 4 + 3 + 2 - 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Counting Solutions\n",
    "\n",
    "Alex Bellos had another challenge:  \n",
    "\n",
    "> I was half hoping a computer scientist would let me know exactly how many solutions there are with only the four basic operations. Maybe someone will. \n",
    "\n",
    "As it stands, my program can't answer that question, because I only keep one expression for each value. \n",
    "\n",
    "Also, I'm not sure what it means to be a distinct solution. For example, are `((10+9)+8)` and `(10+(9+8))` different, or are they same, because they both are equivalent to `(10+9+8)`? Similarly, are `((3-2)-1)` and `(3-(2+1)` different, or the same because they both are equivalent to `(3 + -2 + -1)`? I think the notion of \"distinct solution\" is just inherently ambiguous, and each of these questions could reasonably be answered either way. My choice is to count each of these as distinct: every expression has exactly ten numbers, nine operators, and nine pairs of brackets, and if an expression differs in any character, it is different. But I won't argue with anyone who has a different definition of \"distinct solution.\"\n",
    "\n",
    "So how can I count expressions? One approach would be to go back to enumerating every equation (all 4862 &times; 4<sup>9</sup> = 1.2 bilion of them) and checking which ones equal 2016. That would take about 40 hours with my Python program, but I could get it under 40 minutes in a more efficient language.\n",
    "\n",
    "Another approach is to count subexpressions as the table is filled in. We won't enumerate all the expressions, just count them. I'll introduce a second table, `COUNTS`, such that\n",
    "\n",
    "    COUNTS[(10, 9, 8)][27] == 2\n",
    "    \n",
    "because there are 2 ways to make 27 with the numbers `(10, 9, 8)`, namely, `((10+9)+8)` and `(10+(9+8))`.\n",
    "How do we compute the counts? By looking at every split and operator choice that can make the value, and summing up (over all of these) the product of the counts for the two sides.  For example, there are 2 ways to make 27 with `(10 ... 8)`, and it turns out there are 3526 ways to make 1 with `(7 ... 1)`. So there are 2 &times; 3526 = 7052 ways to make 28 with this split by adding 27 and 1. \n",
    "\n",
    "I'll make `expr` handle `COUNTS` as well as `EXPS`. And I'll define  `clear` to clear out the cache of `COUNTS` and `EXPS`, so that we can fill the tables with our new, improved entries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "COUNTS = defaultdict(Counter) # e.g., COUNTS[(10, 9, 8)][27] == 2\n",
    "\n",
    "def expressions(numbers):\n",
    "    \"Fill EXPS table for numbers, and all sub-sequences of numbers. Return EXPS[numbers]\"\n",
    "    if numbers in EXPS: # Already did the work\n",
    "        pass\n",
    "    elif len(numbers) == 1: # Only one way to make an expression out of a single number\n",
    "        expr(numbers, numbers[0], str(numbers[0]), 1)\n",
    "    else: # Split in all ways; fill tables for left and right; combine tables in all ways\n",
    "        for (Lnums, Rnums) in splits(numbers):\n",
    "            for (L, R) in itertools.product(expressions(Lnums), expressions(Rnums)):\n",
    "                Lexp, Rexp = '(' + EXPS[Lnums][L], EXPS[Rnums][R] + ')'\n",
    "                count = COUNTS[Lnums][L] * COUNTS[Rnums][R]\n",
    "                if R != 0: \n",
    "                    expr(numbers, L / R, Lexp + '/' + Rexp, count)\n",
    "                expr(numbers, L * R, Lexp + '*' + Rexp, count)\n",
    "                expr(numbers, L - R, Lexp + '-' + Rexp, count)\n",
    "                expr(numbers, L + R, Lexp + '+' + Rexp, count)\n",
    "    return EXPS[numbers]\n",
    "\n",
    "def expr(numbers, val, exp, count):\n",
    "    \"Fill EXPS[numbers][val] with exp, and increment COUNTS.\"\n",
    "    EXPS[numbers][val] = exp\n",
    "    COUNTS[numbers][val] += count\n",
    "    \n",
    "def clear(): EXPS.clear(); COUNTS.clear()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{-62: '(10-(9*8))',\n",
       " -7: '((10-9)-8)',\n",
       " -6.888888888888889: '((10/9)-8)',\n",
       " 0.125: '((10-9)/8)',\n",
       " 0.1388888888888889: '((10/9)/8)',\n",
       " 0.5882352941176471: '(10/(9+8))',\n",
       " 2.375: '((10+9)/8)',\n",
       " 8: '((10-9)*8)',\n",
       " 8.875: '(10-(9/8))',\n",
       " 8.88888888888889: '((10/9)*8)',\n",
       " 9: '((10-9)+8)',\n",
       " 9.11111111111111: '((10/9)+8)',\n",
       " 10.0: '(10*(9-8))',\n",
       " 11: '((10+9)-8)',\n",
       " 11.125: '(10+(9/8))',\n",
       " 11.25: '((10*9)/8)',\n",
       " 27: '((10+9)+8)',\n",
       " 82: '((10*9)-8)',\n",
       " 98: '((10*9)+8)',\n",
       " 152: '((10+9)*8)',\n",
       " 170: '(10*(9+8))',\n",
       " 720: '((10*9)*8)'}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clear()\n",
    "expressions((10, 9, 8))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Counter({-62: 1,\n",
       "         -7: 2,\n",
       "         -6.888888888888889: 1,\n",
       "         0.125: 1,\n",
       "         0.1388888888888889: 2,\n",
       "         0.5882352941176471: 1,\n",
       "         2.375: 1,\n",
       "         8: 1,\n",
       "         8.875: 1,\n",
       "         8.88888888888889: 2,\n",
       "         9: 2,\n",
       "         9.11111111111111: 1,\n",
       "         10.0: 2,\n",
       "         11: 2,\n",
       "         11.125: 1,\n",
       "         11.25: 2,\n",
       "         27: 2,\n",
       "         82: 2,\n",
       "         98: 1,\n",
       "         152: 1,\n",
       "         170: 1,\n",
       "         720: 2})"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "COUNTS[(10, 9, 8)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "COUNTS[(10, 9, 8)][27]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Looks good to me. Now let's repeat the computation, this time keeping track of `COUNTS`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2min 10s, sys: 5.36 s, total: 2min 16s\n",
      "Wall time: 3min 4s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'(((((((10+((9*8)*7))-6)-5)*4)+3)+2)-1)'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clear()\n",
    "\n",
    "%time expressions(c10)[2016]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# The Answer (?)\n",
    "\n",
    "Now we can read off the answer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "30066"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "COUNTS[c10][2016]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "This says there are 30,066 distinct expressions for 2016. \n",
    "\n",
    "**But I don't believe it.**\n",
    "\n",
    "We'll see why in a bit, but first some trivia questions to answer:\n",
    "\n",
    "- How many distinct values can be made?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5789961"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(expressions(c10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "- What's the smallest positive integer than cannot be made?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10843"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import itertools \n",
    "\n",
    "def unmakeable(numbers):\n",
    "    \"Smallest positive integer than can't be made by numbers.\"\n",
    "    return next(i for i in itertools.count(0) if i not in expressions(numbers))\n",
    "\n",
    "unmakeable(c10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "- What is the expected theoretical number of expressions? It is [Catalan(9)](http://www.wolframalpha.com/input/?i=9th+catalan+number) &times; 4<sup>9</sup>:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1274544128"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "4862 * 4 ** 9"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "- How many expressions were actually entered in the `COUNTS` table?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1264876734"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum(COUNTS[c10].values())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "So, about 1% of the 1.27 billion theoretically possible expressions do not appear in `COUNTS`; these are the `ZeroDivisionErrors`.\n",
    "\n",
    "# Dealing with Round-off Errors\n",
    "\n",
    "Why don't I believe the answer of  30,066 expressions? Because floating point division can have round-off errors.  For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2015.9999999999998"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "2015 + 1/3 + 1/3 + 1/3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "2015 + 1/3 + 1/3 + 1/3 == 2016"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "So there might be perfectly good solutions that are hiding in the `EXPS` table under 2015.9999999999998 (or some similar number) when they should be exactly 2016. Let's find all the values that are very near to 2016:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{2015.999999999997,\n",
       " 2015.999999999999,\n",
       " 2015.9999999999993,\n",
       " 2015.9999999999995,\n",
       " 2015.9999999999998,\n",
       " 2016.0,\n",
       " 2016.0000000000002,\n",
       " 2016.0000000000005,\n",
       " 2016.0000000000018,\n",
       " 2016.000000000002,\n",
       " 2016.0000000000023}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "{val for val in expressions(c10)\n",
    " if abs(val - 2016) < 0.0001}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "I suspect that all of these actually should be exactly 2016. \n",
    "\n",
    "To find out for sure, let's re-do all the calculations using exact rational arithmetic, as provided by the `fractions.Fraction` data type. From experience I know that this will be an order of magnitude slower, so we're looking at maybe a 20 minute computation.\n",
    "\n",
    "I'll replace the computation `L / R` with `divide(L, R)`, which calls `Fraction`. To mitigate the expense of this computation, I make two optimizations. First, `divide` replaces a whole fraction, such as `Fraction(6, 2)`, with an `int`, such as `3`. Second, I modify `expr` to *not* fill in the `EXPS[c10]` table, except for `EXPS[c10][2016]`. The rationale is that we don't need the other entries, and by not storing them, we save a lot of memory, and thus save garbage collection time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from fractions import Fraction\n",
    "\n",
    "def expressions(numbers):\n",
    "    \"Fill EXPS table for numbers, and all sub-sequences of numbers. Return EXPS[numbers]\"\n",
    "    if numbers in EXPS: # Already did the work\n",
    "        pass\n",
    "    elif len(numbers) == 1: # Only one way to make an expression out of a single number\n",
    "        expr(numbers, numbers[0], str(numbers[0]), 1)\n",
    "    else: # Split in all ways; fill tables for left and right; combine tables in all ways\n",
    "        for (Lnums, Rnums) in splits(numbers):\n",
    "            for (L, R) in itertools.product(expressions(Lnums), expressions(Rnums)):\n",
    "                Lexp, Rexp = '(' + EXPS[Lnums][L], EXPS[Rnums][R] + ')'\n",
    "                count = COUNTS[Lnums][L] * COUNTS[Rnums][R]\n",
    "                if R != 0: \n",
    "                    expr(numbers, divide(L, R), Lexp + '/' + Rexp, count)\n",
    "                expr(numbers, L * R, Lexp + '*' + Rexp, count)\n",
    "                expr(numbers, L - R, Lexp + '-' + Rexp, count)\n",
    "                expr(numbers, L + R, Lexp + '+' + Rexp, count)\n",
    "    return EXPS[numbers]\n",
    "\n",
    "def divide(L, R):\n",
    "    \"Exact rational division of L/R.\"\n",
    "    f = Fraction(L, R)\n",
    "    return f.numerator if f.denominator == 1 else f\n",
    "\n",
    "def expr(numbers, value, exp, count):\n",
    "    \"Fill EXPS[numbers][val] with exp, and increment COUNTS.\"\n",
    "    if numbers == c10 and value != 2016: \n",
    "        return\n",
    "    EXPS[numbers][value] = exp\n",
    "    COUNTS[numbers][value] += count"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# The Answer (!)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "clear()\n",
    "\n",
    "%time expressions(c10)[2016]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "COUNTS[c10][2016]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "That did indeed take about ten times longer, but we now have an answer that I have more confidence in (but I wouldn't accept it as definitive until it was independently verified or I had an extensive tst suite). And of course, if you have a different definition of \"distinct solution,\" you will get a different answer."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Dealing with the Exponentiation Operator\n",
    "\n",
    "Now let's turn to another of Alex's puzzles: making 2016 and other target values from a string of four or five `4`s,  with exponentiation allowed. Exponentiation is tricky for five reasons:\n",
    "\n",
    "- **Division by zero**: `(0 ** -1)` is the same as `(1 / 0)`, and gives a `ZeroDivisionError`.\n",
    "- **Irrationals**: `(2 ** (1 / 2))` is an irrational number; so we can't do exact rational arithmetic.\n",
    "- **Imaginaries**: `(-1 ** (1 / 2))` is an imaginary number, but Python gives a `ValueError`.\n",
    "- **Overflow**: `(10. ** (9. ** 8.))`, as a `float`, gives a `OverflowError`.\n",
    "- **Finite memory**: [`(10 ** (9 ** (8 * 7)))`](http://www.wolframalpha.com/input/?i=10+%5E+9+%5E+56), as an `int`, gives an `OutOfMemoryError` (even if your memory was expanded to use every atom in the universe).\n",
    "\n",
    "How do we deal with this? We can't do exact rational arithmetic. We could try to do exact *algebra*, perhaps using [SymPy](http://www.sympy.org/en/index.html), but that seems difficult\n",
    "and computationally expensive, so instead I will abandon the goal of exact computation, and do everything in the domain of floats (reluctantly accepting that there will be some round-off errors). We'll coerce numbers to floats when we first put them in the table, and all subsequent operations will be with floats. I define a new function, `expr2`,  to call `expr`, catching arithmetic errors. Since we are making some rather arbitrary decisions about what expressions are allowed (e.g. imaginary numbers are not), I'll give up on trying to maintain `COUNTS`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from operator import add, sub, mul, truediv\n",
    "\n",
    "def expressions(numbers):\n",
    "    \"Fill EXPS table for numbers, and all sub-sequences of numbers. Return EXPS[numbers]\"\n",
    "    if numbers in EXPS: # Already did the work\n",
    "        pass\n",
    "    elif len(numbers) == 1: # Only one way to make an expression out of a single number\n",
    "        expr(numbers, float(numbers[0]), str(numbers[0]))\n",
    "    else: # Split in all ways; fill tables for left and right; combine tables in all ways\n",
    "        for (Lnums, Rnums) in splits(numbers):\n",
    "            for (L, R) in itertools.product(expressions(Lnums), expressions(Rnums)):\n",
    "                Lexp, Rexp = '(' + EXPS[Lnums][L], EXPS[Rnums][R] + ')'\n",
    "                expr2(numbers, L, pow,     R, Lexp + '**' + Rexp)\n",
    "                expr2(numbers, L, truediv, R, Lexp + '/'  + Rexp)\n",
    "                expr2(numbers, L, mul,     R, Lexp + '*'  + Rexp)\n",
    "                expr2(numbers, L, add,     R, Lexp + '+'  + Rexp)\n",
    "                expr2(numbers, L, sub,     R, Lexp + '-'  + Rexp)\n",
    "    return EXPS[numbers]\n",
    "\n",
    "def expr2(numbers, L, op, R, exp): \n",
    "    \"Fill table entries for op(L, R), catching errors.\"\n",
    "    try:\n",
    "        expr(numbers, op(L, R), exp)\n",
    "    except (ArithmeticError, ValueError):\n",
    "        pass\n",
    "    \n",
    "def expr(numbers, value, exp): EXPS[numbers][value] = exp"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Now we can solve the \"2016 with five fours\" puzzle:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "clear()\n",
    "\n",
    "expressions((4, 4, 4, 4, 4))[2016]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "I'll define a function to create a table of makeable integers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def makeable(numbers):\n",
    "    \"A table of {i: expression} for all integers i from 0 up to first unmakeable.\"\n",
    "    targets = range(unmakeable(numbers))\n",
    "    return {i: expressions(numbers)[i]\n",
    "            for i in targets}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We'll use this to see if we can solve the \"0 to 9 with four fours\" puzzle:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "makeable((4, 4, 4, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Yes: we can get 0 to 9 (but not 10).\n",
    "\n",
    "Now I'll see what integers we can make with five fives. Legend has it that you can get all the way up to 55:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "ff = (5, 5, 5, 5, 5)\n",
    "\n",
    "makeable(ff)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We didn't get there. \n",
    "\n",
    "# More Operations\n",
    "\n",
    "With some research, I [see](http://www.infobarrel.com/Five_Fives_Problem_Recreational_Mathematics) that others who got up to 55 with five 5s used these three concepts:\n",
    "\n",
    "- **digit concatenation**: `55`\n",
    "- **decimal point**: `.5`\n",
    "- **unary operations**: \n",
    "  - **factorial**: `5! = 120` \n",
    "  - **square root**:  &radic; `5`\n",
    "\n",
    "\n",
    "We'll refactor `expressions` to call these three new subfunctions:\n",
    "\n",
    "- `digit_expressions`: For every subsequence of numbers, we'll smush the digits together, and then make a table entry for those resulting digits as an integer, and with a decimal point in each possible position.\n",
    "- `binary_expressions`: The code that previously was the main body of `expressions`.\n",
    "- `unary_expressions`: Apply the unary operators to every entry in the table. (Because it applies to entries already in the table, make sure to call `unary_expressions` last.)\n",
    "\n",
    "We'll still do all computation in the domain of floats."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from math import sqrt, factorial\n",
    "\n",
    "def expressions(numbers):\n",
    "    \"Fill EXPS table for numbers, and all sub-sequences of numbers. Return EXPS[numbers]\"\n",
    "    if numbers not in EXPS: \n",
    "        digit_expressions(numbers)\n",
    "        binary_expressions(numbers)\n",
    "        unary_expressions(numbers)\n",
    "    return EXPS[numbers]\n",
    "\n",
    "def digit_expressions(numbers):\n",
    "    \"Fill tables with expressions made from the digits of numbers, and a decimal point.\"\n",
    "    exp = ''.join(str(n) for n in numbers)\n",
    "    expr(numbers, float(exp), exp)\n",
    "    for d in range(len(exp)):\n",
    "        decimal = exp[:d] + '.' + exp[d:]\n",
    "        expr(numbers, float(decimal), decimal)\n",
    "            \n",
    "def binary_expressions(numbers):\n",
    "    \"Fill tables with all expressions formed by splitting numbers and combining with an op.\"\n",
    "    for (Lnums, Rnums) in splits(numbers):\n",
    "        for (L, R) in itertools.product(expressions(Lnums), expressions(Rnums)):\n",
    "            Lexp, Rexp = '(' + EXPS[Lnums][L], EXPS[Rnums][R] + ')'\n",
    "            if 1 <= R <= 10 and (L > 0 or int(R) == R):\n",
    "                expr2(numbers, L, pow, R, Lexp + '**' + Rexp)\n",
    "            expr2(numbers, L, truediv, R, Lexp + '/'  + Rexp)\n",
    "            expr2(numbers, L, mul,     R, Lexp + '*'  + Rexp)\n",
    "            expr2(numbers, L, add,     R, Lexp + '+'  + Rexp)\n",
    "            expr2(numbers, L, sub,     R, Lexp + '-'  + Rexp)\n",
    "            \n",
    "def unary_expressions(numbers):\n",
    "    for v in list(EXPS[numbers]):\n",
    "        exp = EXPS[numbers][v]\n",
    "        if v > 0: \n",
    "            expr(numbers, sqrt(v), '√' + exp)\n",
    "        if 2 <= v <= 6 and v == int(v):\n",
    "            expr(numbers, factorial(v), exp + '!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Now that we have more variety in the types of expressions formed, I want to choose a \"good\" expression to represent each value. I'll modify `expr` so that when there are multiple expressions for a value, it chooses the one with the least \"weight,\" where I define `weight` as the length of the string, plus a penalty of 1 for every square root sign (just because square root feels \"heavier\" than the other operations):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def expr(numbers, value, exp): \n",
    "    if value not in EXPS[numbers] or weight(exp) < weight(EXPS[numbers][value]):\n",
    "        EXPS[numbers][value] = exp\n",
    "        \n",
    "def weight(exp): return len(exp) + exp.count('√')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We'll try again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "clear()\n",
    "\n",
    "%time makeable(ff)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Wow! We almost tripled the 55 goal! I have to say, I would never have come up with the solution for 81 on my own. It works because (√(5 - .5) \\* √0.5) = √(4.5 \\* 0.5) = (√2.25) = 1.5."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Even More Operations \n",
    "\n",
    "At the risk of making the computation take even longer, I'm going to add two more operations:\n",
    "\n",
    "- **Floor**: &lfloor;*x*&rfloor; is the largest integer less than or equal to *x* (in other words, rounding down).\n",
    "- **Ceiling**: &lceil;*x*&rceil; is the smallest integer greater than or equal to *x* (in other words, rounding up).\n",
    "\n",
    "These operations are useful because they produce integers, and our targets are the integers (from 0 up to whatever). \n",
    "\n",
    "In addition, I'll allow two consecutive applications of unary operators, thus allowing expressions such as\n",
    "\n",
    "- ⌊√5⌋ = 2\n",
    "- ⌈5.5⌉! = 720\n",
    "\n",
    "But still not allowing three consecutive applications, such as\n",
    "\n",
    "- ⌈√5⌉! = 6\n",
    "\n",
    "To compensate for these new expressions, I'll be pickier about when I allow the square root function to apply."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from math import floor, ceil\n",
    "\n",
    "def unary_expressions(numbers):\n",
    "    for i in range(2):\n",
    "        for v in list(EXPS[numbers]):\n",
    "            exp = EXPS[numbers][v]\n",
    "            if 0 < v <= 100 and 4*v == round(4*v):\n",
    "                expr(numbers, sqrt(v), '√' + exp)\n",
    "            if 2 <= v <= 6 and v == round(v):\n",
    "                expr(numbers, factorial(v), exp + '!')\n",
    "            if v != round(v):\n",
    "                uexp = unbracket(exp)\n",
    "                expr(numbers, floor(v), '⌊' + uexp + '⌋')\n",
    "                expr(numbers, ceil(v),  '⌈' + uexp + '⌉')\n",
    "            \n",
    "def unbracket(exp):\n",
    "    \"Remove outer brackets from exp if they are there.\"\n",
    "    if exp.startswith('(') and exp.endswith(')'):\n",
    "        return exp[1:-1]\n",
    "    else:\n",
    "        return exp"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Let's try:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "clear()\n",
    "\n",
    "%time makeable(ff)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "The output got truncated by Jupyter Notebook after 1000 entries. Let's see what the first unmakeable integer actually is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "unmakeable(ff)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "I think we've conquered the five 5s problem.\n",
    "\n",
    "# Conclusion\n",
    "\n",
    "We were able to solve the puzzles, and we now have some tools to explore new puzzles. What can you discover?"
   ]
  }
 ],
 "metadata": {
  "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.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
