{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "xkcd 1313: Regex Golf (Part 2: Infinite Problems)\n",
    "====\n",
    "\n",
    "<p style=\"text-align: right\"><i>Peter Norvig<br>with Stefan Pochmann<br>Feb 2014<br>revised Nov 2015</i></p>\n",
    "\n",
    "\n",
    "\n",
    "<a href=\"http://xkcd.com/1313\"><img src=\"http://imgs.xkcd.com/comics/regex_golf.png\"></a>\n",
    "\n",
    "This Again?\n",
    "----\n",
    "\n",
    "Last month I demonstrated [a simple Regex Golf program](http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313.ipynb?create=1). I thought that was the end of the topic, but [Stefan Pochmann](http://www.stefan-pochmann.info/spocc/) sent me a series of emails suggesting some impressive improvements. ([Davide Canton](https://plus.sandbox.google.com/108324296451294887432/posts) and [Thomas Breuel](https://plus.google.com/118190679520611168174/posts) also had good suggestions.) So this post is an exploration of some of Stefan's new ideas, and some of my own. It's a story about regex golf, and about using exploratory programming to test out ideas.\n",
    "\n",
    "To review, here's the program from [part 1](http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313.ipynb?create=1), with some minor modifications:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from __future__ import division, print_function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from collections import Counter, defaultdict\n",
    "import re\n",
    "import itertools\n",
    "import random \n",
    "\n",
    "Set = frozenset # Data will be frozensets, so they can't be mutated.\n",
    "\n",
    "def words(text):\n",
    "    \"All space-separated words in text.\"\n",
    "    return Set(text.split())\n",
    "\n",
    "def phrases(text, sep='/'): \n",
    "    \"All sep-separated phrases in text, uppercased and stripped.\"\n",
    "    return Set(p.upper().strip() for p in text.split(sep))\n",
    "\n",
    "def mistakes(regex, winners, losers):\n",
    "    \"The set of mistakes made by this regex in classifying winners and losers.\"\n",
    "    return ({\"Should have matched: \" + W \n",
    "             for W in winners if not re.search(regex, W)} |\n",
    "            {\"Should not have matched: \" + L \n",
    "             for L in losers if re.search(regex, L)})\n",
    "\n",
    "def findregex(winners, losers, k=4):\n",
    "    \"Find a regex that matches all winners but no losers (sets of strings).\"\n",
    "    # Make a pool of regex parts, then pick from them to cover winners.\n",
    "    # On each iteration, add the 'best' part to 'solution',\n",
    "    # remove winners covered by best, and keep in 'pool' only parts\n",
    "    # that still match some winner.\n",
    "    pool = regex_parts(winners, losers)\n",
    "    solution = []\n",
    "    def score(p): return k * len(matches(p, winners)) - len(p)\n",
    "    while winners:\n",
    "        best = max(pool, key=score)\n",
    "        solution.append(best)\n",
    "        winners = winners - matches(best, winners)\n",
    "        pool = {p for p in pool if matches(p, winners)}\n",
    "    return OR(solution)\n",
    "\n",
    "def matches(regex, strings):\n",
    "    \"Return a set of all the strings that are matched by regex.\"\n",
    "    return {s for s in strings if re.search(regex, s)}\n",
    "\n",
    "OR  = '|'.join # Join a sequence of strings with '|' between them\n",
    "cat = ''.join  # Join a sequence of strings with nothing between them\n",
    "\n",
    "def regex_parts(winners, losers):\n",
    "    \"Return parts that match at least one winner, but no loser.\"\n",
    "    wholes = {'^' + w + '$' for w in winners}\n",
    "    parts = {d for w in wholes for p in subparts(w) for d in dotify(p)}\n",
    "    return wholes | {p for p in parts if not matches(p, losers)}\n",
    "\n",
    "def subparts(word):\n",
    "    \"Return a set of subparts of word: consecutive characters up to length 4.\"\n",
    "    return set(word[i:i+n] for i in range(len(word)) for n in (1, 2, 3, 4)) \n",
    "    \n",
    "def dotify(part):\n",
    "    \"Return all ways to replace a subset of chars in part with '.'.\"\n",
    "    choices = map(replacements, part)\n",
    "    return {cat(chars) for chars in itertools.product(*choices)}\n",
    "\n",
    "def replacements(c): \n",
    "    \"All ways to replace character c with something interesting: for now, 'c' or '.'.\"\n",
    "    return c if c in '^$' else c + '.'\n",
    "\n",
    "def report(winners, losers):\n",
    "    \"Find a regex to match A but not B, and vice-versa.  Print summary.\"\n",
    "    solution = findregex(winners, losers)\n",
    "    assert not mistakes(solution, winners, losers)\n",
    "    print('Chars: {}, ratio: {:.1f}, inputs: {}:{}'.format(\n",
    "          len(solution), len(trivial(winners)) / len(solution) , len(winners), len(losers)))\n",
    "    return solution\n",
    "\n",
    "def trivial(winners): return '^(' + OR(winners) + ')$'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Here are some \"arbitrary lists\" (see panel two of the comic) which we will be using to test out the code. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "winners = words('''washington adams jefferson jefferson madison madison monroe \n",
    "    monroe adams jackson jackson van-buren harrison polk taylor pierce buchanan \n",
    "    lincoln lincoln grant grant hayes garfield cleveland harrison cleveland mckinley\n",
    "    mckinley roosevelt taft wilson wilson harding coolidge hoover roosevelt \n",
    "    roosevelt roosevelt roosevelt truman eisenhower eisenhower kennedy johnson nixon \n",
    "    nixon carter reagan reagan bush clinton clinton bush bush obama obama''')\n",
    "losers = words('''clinton jefferson adams pinckney pinckney clinton king adams \n",
    "    jackson adams clay van-buren van-buren clay cass scott fremont breckinridge \n",
    "    mcclellan seymour greeley tilden hancock blaine cleveland harrison bryan bryan \n",
    "    parker bryan roosevelt hughes cox davis smith hoover landon wilkie dewey dewey \n",
    "    stevenson stevenson nixon goldwater humphrey mcgovern ford carter mondale \n",
    "    dukakis bush dole gore kerry mccain romney''') - winners\n",
    "\n",
    "boys = words('jacob mason ethan noah william liam jayden michael alexander aiden')\n",
    "girls = words('sophia emma isabella olivia ava emily abigail mia madison elizabeth')\n",
    "\n",
    "pharma = words('lipitor nexium plavix advair ablify seroquel singulair crestor actos epogen')\n",
    "cities = words('paris trinidad capetown riga zurich shanghai vancouver chicago adelaide auckland')\n",
    "\n",
    "foo = words('''afoot catfoot dogfoot fanfoot foody foolery foolish fooster footage foothot footle footpad footway \n",
    "    hotfoot jawfoot mafoo nonfood padfoot prefool sfoot unfool''')\n",
    "bar = words('''Atlas Aymoro Iberic Mahran Ormazd Silipan altared chandoo crenel crooked fardo folksy forest \n",
    "    hebamic idgah manlike marly palazzi sixfold tarrock unfold''')\n",
    "\n",
    "nouns = words('''time year people way day man thing woman life child world school \n",
    "    state family student group country problem hand part place case week company \n",
    "    system program question work government number night point home water room \n",
    "    mother area money story fact month lot right study book eye job word business \n",
    "    issue side kind head house service friend father power hour game line end member \n",
    "    law car city community name president team minute idea kid body information \n",
    "    back parent face others level office door health person art war history party result \n",
    "    change morning reason research girl guy moment air teacher force education''')\n",
    "adverbs = words('''all particularly just less indeed over soon course still yet before \n",
    "    certainly how actually better to finally pretty then around very early nearly now \n",
    "    always either where right often hard back home best out even away enough probably \n",
    "    ever recently never however here quite alone both about ok ahead of usually already \n",
    "    suddenly down simply long directly little fast there only least quickly much forward \n",
    "    today more on exactly else up sometimes eventually almost thus tonight as in close \n",
    "    clearly again no perhaps that when also instead really most why ago off \n",
    "    especially maybe later well together rather so far once''') - nouns  \n",
    "verbs = words('''ask believe borrow break bring buy can be able cancel change clean\n",
    "    comb complain cough count cut dance draw drink drive eat explain fall\n",
    "    fill find finish fit fix fly forget give go have hear hurt know learn\n",
    "    leave listen live look lose make do need open close shut organise pay\n",
    "    play put rain read reply run say see sell send sign sing sit sleep\n",
    "    smoke speak spell spend stand start begin study succeed swim take talk\n",
    "    teach tell think translate travel try turn off turn on type understand\n",
    "    use wait wake up want watch work worry write''') - nouns\n",
    "\n",
    "randoms = Set(vars(random))\n",
    "builtins = Set(vars(__builtin__)) - randoms\n",
    "\n",
    "starwars = phrases('''The Phantom Menace / Attack of the Clones / Revenge of the Sith /\n",
    "    A New Hope / The Empire Strikes Back / Return of the Jedi''')\n",
    "startrek = phrases('''The Wrath of Khan / The Search for Spock / The Voyage Home /\n",
    "    The Final Frontier / The Undiscovered Country / Generations / First Contact /\n",
    "    Insurrection / Nemesis''')\n",
    "\n",
    "dogs = phrases(''''Labrador Retrievers / German Shepherd Dogs / Golden Retrievers / Beagles / Bulldogs / \n",
    "    Yorkshire Terriers / Boxers / Poodles / Rottweilers / Dachshunds / Shih Tzu / Doberman Pinschers / \n",
    "    Miniature Schnauzers / French Bulldogs / German Shorthaired Pointers / Siberian Huskies / Great Danes / \n",
    "    Chihuahuas / Pomeranians / Cavalier King Charles Spaniels / Shetland Sheepdogs / Australian Shepherds / \n",
    "    Boston Terriers / Pembroke Welsh Corgis / Maltese / Mastiffs / Cocker Spaniels / Havanese / \n",
    "    English Springer Spaniels / Pugs / Brittanys / Weimaraners / Bernese Mountain Dogs / Vizslas / Collies / \n",
    "    West Highland White Terriers / Papillons / Bichons Frises / Bullmastiffs / Basset Hounds / \n",
    "    Rhodesian Ridgebacks / Newfoundlands / Russell Terriers / Border Collies / Akitas / \n",
    "    Chesapeake Bay Retrievers / Miniature Pinschers / Bloodhounds / St. Bernards / Shiba Inu / Bull Terriers / \n",
    "    Chinese Shar-Pei / Soft Coated Wheaten Terriers / Airedale Terriers / Portuguese Water Dogs / Whippets / \n",
    "    Alaskan Malamutes / Scottish Terriers / Australian Cattle Dogs / Cane Corso / Lhasa Apsos / \n",
    "    Chinese Crested / Cairn Terriers / English Cocker Spaniels / Dalmatians / Italian Greyhounds / \n",
    "    Dogues de Bordeaux / Samoyeds / Chow Chows / German Wirehaired Pointers / Belgian Malinois / \n",
    "    Great Pyrenees / Pekingese / Irish Setters / Cardigan Welsh Corgis / Staffordshire Bull Terriers / \n",
    "    Irish Wolfhounds / Old English Sheepdogs / American Staffordshire Terriers / Bouviers des Flandres / \n",
    "    Greater Swiss Mountain Dogs / Japanese Chin / Tibetan Terriers / Brussels Griffons / \n",
    "    Wirehaired Pointing Griffons / Border Terriers / English Setters / Basenjis / Standard Schnauzers / \n",
    "    Silky Terriers / Flat-Coated Retrievers / Norwich Terriers / Afghan Hounds / Giant Schnauzers / Borzois / \n",
    "    Wire Fox Terriers / Parson Russell Terriers / Schipperkes / Gordon Setters / Treeing Walker Coonhounds''')\n",
    "cats = phrases('''Abyssinian / Aegean cat / Australian Mist / American Curl / American Bobtail / \n",
    "    American Polydactyl / American Shorthair / American Wirehair / Arabian Mau / Asian / Asian Semi-longhair / \n",
    "    Balinese / Bambino / Bengal / Birman / Bombay / Brazilian Shorthair / British Shorthair / British Longhair / \n",
    "    Burmese / Burmilla / California Spangled Cat / Chantilly/Tiffany / Chartreux / Chausie / Cheetoh / \n",
    "    Colorpoint Shorthair / Cornish Rex / Cymric / Cyprus cat / Devon Rex / Donskoy or Don Sphynx / Dragon Li / \n",
    "    Dwelf / Egyptian Mau / European Shorthair / Exotic Shorthair / German Rex / Havana Brown / Highlander / \n",
    "    Himalayan-Colorpoint Persian / Japanese Bobtail / Javanese / Khao Manee / Korat / Korn Ja / \n",
    "    Kurilian Bobtail / LaPerm / Maine Coon / Manx / Mekong bobtail / Minskin / Munchkin / Nebelung / Napoleon / \n",
    "    Norwegian Forest Cat / Ocicat / Ojos Azules / Oregon Rex / Oriental Bicolor / Oriental Shorthair / \n",
    "    Oriental Longhair / Persian / Peterbald / Pixie-bob / Ragamuffin / Ragdoll / Russian Blue / Russian Black / \n",
    "    Sam Sawet / Savannah / Scottish Fold / Selkirk Rex / Serengeti cat / Serrade petit / Siamese / Siberian / \n",
    "    Singapura / Snowshoe / Sokoke / Somali / Sphynx / Swedish forest cat / Thai / Tonkinese / Toyger / \n",
    "    Turkish Angora / Turkish Van / Ukrainian Levkoy / York Chocolate Cat''')\n",
    "\n",
    "movies = phrases('''Citizen Kane / The Godfather / Vertigo / 2001: A Space Odyssey / The Searchers / Sunrise / \n",
    "    Singin’ in the Rain / Psycho / Casablanca / The Godfather Part II / The Magnificent Ambersons / Chinatown / \n",
    "    North by Northwest / Nashville / The Best Years of Our Lives / McCabe & Mrs Miller / The Gold Rush / \n",
    "    City Lights / Taxi Driver / Goodfellas / Mulholland Drive / Greed / Annie Hall / The Apartment / \n",
    "    Do the Right Thing / Killer of Sheep / Barry Lyndon / Pulp Fiction / Raging Bull / Some Like It Hot / \n",
    "    A Woman Under the Influence / The Lady Eve / The Conversation / The Wizard of Oz / Double Indemnity / \n",
    "    Star Wars / Imitation of Life / Jaws / The Birth of a Nation / Meshes of the Afternoon / Rio Bravo / \n",
    "    Dr Strangelove / Letter from an Unknown Woman / Sherlock Jr / The Man Who Shot Liberty Valance / \n",
    "    It’s a Wonderful Life / Marnie / A Place in the Sun / Days of Heaven / His Girl Friday / Touch of Evil / \n",
    "    The Wild Bunch / Grey Gardens / Sunset Boulevard / The Graduate / Back to the Future / Crimes and Misdemeanors / \n",
    "    The Shop Around the Corner / One Flew Over the Cuckoo’s Nest / Blue Velvet / Eyes Wide Shut / The Shining / \n",
    "    Love Streams / Johnny Guitar / The Right Stuff / Red River / Modern Times / Notorious / Koyaanisqatsi / \n",
    "    The Band Wagon / Groundhog Day / The Shanghai Gesture / Network / Forrest Gump / \n",
    "    Close Encounters of the Third Kind / The Empire Strikes Back / Stagecoach / Schindler’s List / \n",
    "    The Tree of Life / Meet Me in St Louis / Thelma & Louise / Raiders of the Lost Ark / Bringing Up Baby / \n",
    "    Deliverance / Night of the Living Dead / The Lion King / Eternal Sunshine of the Spotless Mind / \n",
    "    West Side Story / In a Lonely Place / Apocalypse Now / ET: The Extra-Terrestrial / The Night of the Hunter / \n",
    "    Mean Streets / 25th Hour / Duck Soup / The Dark Knight / Gone With the Wind / Heaven’s Gate / 12 Years a Slave / \n",
    "    Ace in the Hole''')\n",
    "tv = phrases('''The Abbott and Costello Show / ABC’s Wide World of Sports / Alfred Hitchcock Presents /\n",
    "    All in the Family / An American Family / American Idol / Arrested Development / Battlestar Galactica /\n",
    "    The Beavis and Butt-Head Show / The Bob Newhart Show / Brideshead Revisited / Buffalo Bill /\n",
    "    Buffy the Vampire Slayer / The Carol Burnett Show / The CBS Evening News with Walter Cronkite /\n",
    "    A Charlie Brown Christmas / Cheers / The Cosby Show / The Daily Show / Dallas / The Day After / \n",
    "    Deadwood / The Dick Van Dyke Show / Dragnet / The Ed Sullivan Show / The Ernie Kovacs Show /\n",
    "    Felicity / Freaks and Geeks / The French Chef / Friends / General Hospital /\n",
    "    The George Burns and Gracie Allen Show / Gilmore Girls / Gunsmoke / Hill Street Blues /\n",
    "    Homicide: Life on the Street / The Honeymooners / I, Claudius / I Love Lucy / King of the Hill /\n",
    "    The Larry Sanders Show / Late Night with David Letterman / Leave It to Beaver / Lost /\n",
    "    Married with Children / Mary Hartman, Mary Hartman / The Mary Tyler Moore Show / MASH / The Monkees /\n",
    "    Monty Python’s Flying Circus / Moonlighting / My So-Called Life / Mystery Science Theater 3000 /\n",
    "    The Odd Couple / The Office / The Oprah Winfrey Show / Pee Wee’s Playhouse / Playhouse 90 /\n",
    "    The Price Is Right / Prime Suspect / The Prisoner / The Real World / Rocky and His Friends / Roots /\n",
    "    Roseanne / Sanford and Son / Saturday Night Live / Second City Television / See It Now / Seinfeld /\n",
    "    Sesame Street / Sex and the City / The Shield / The Simpsons / The Singing Detective / Six Feet Under /\n",
    "    60 Minutes / Soap / The Sopranos / South Park / SpongeBob SquarePants / SportsCenter / Star Trek /\n",
    "    St Elsewhere / The Super Bowl / Survivor / Taxi /The Tonight Show Starring Johnny Carson /\n",
    "    24 / The Twilight Zone / Twin Peaks / The West Wing / What’s My Line / WKRP in Cincinnati /\n",
    "    The Wire / Wiseguy / The X-Files''')\n",
    "\n",
    "stars = phrases('''Humphrey Bogart / Cary Grant / James Stewart / Marlon Brando / Fred Astaire / Henry Fonda / \n",
    "    Clark Gable / James Cagney / Spencer Tracy / Charlie Chaplin / Gary Cooper / Gregory Peck / John Wayne / \n",
    "    Laurence Olivier / Gene Kelly / Orson Welles / Kirk Douglas / James Dean / Burt Lancaster / Marx Brothers / \n",
    "    Buster Keaton / Sidney Poitier / Robert Mitchum / Edward G. Robinson / William Holden / Katharine Hepburn / \n",
    "    Bette Davis / Audrey Hepburn / Ingrid Bergman / Greta Garbo / Marilyn Monroe / Elizabeth Taylor / Judy Garland / \n",
    "    Marlene Dietrich / Joan Crawford / Barbara Stanwyck / Claudette Colbert / Grace Kelly / Ginger Rogers / \n",
    "    Mae West / Vivien Leigh / Lillian Gish / Shirley Temple / Rita Hayworth / Lauren Bacall / Sophia Loren / \n",
    "    Jean Harlow / Carole Lombard / Mary Pickford / Ava Gardner''')\n",
    "scientists = phrases('''Alain Aspect / Martin Karplus / David Baltimore / Donald Knuth / Allen Bard / \n",
    "    Robert Marks II / Timothy Berners-Lee / Craig Mello / John Tyler Bonner / Luc Montagnier / Dennis Bray / \n",
    "    Gordon Moore / Sydney Brenner / Kary Mullis / Pierre Chambon / C Nüsslein-Volhard / Simon Conway Morris / \n",
    "    Seiji Ogawa / Mildred Dresselhaus / Jeremiah Ostriker / Gerald M Edelman / Roger Penrose / Ronald Evans / \n",
    "    Stanley Prusiner / Anthony Fauci / Henry F Schaefer III / Anthony Fire / Thomas Südhof / Jean Frechet / \n",
    "    Jack Szostak / Margaret Geller / James Tour / Jane Goodall / Charles Townes / Alan Guth / Harold Varmus / \n",
    "    Lene Vestergaard Hau / Craig Venter / Stephen Hawking / James Watson / Peter Higgs / Steven Weinberg / \n",
    "    Leroy Hood / George Whitesides / Eric Kandel / Edward Wilson / Andrew Knoll / Edward Witten / Charles Kao / \n",
    "    Shinya Yamanaka''')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "And here we show how it works:"
   ]
  },
  {
   "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": [
       "' T|E.P|OP'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "solution = findregex(starwars, startrek)\n",
    "solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "not mistakes(solution, starwars, startrek) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Plan of Attack\n",
    "----\n",
    "\n",
    "To improve the program, I'll take the following steps:\n",
    "\n",
    "- *Profiling:* Figure out where the program spends its time.\n",
    "- *Speedup:* Make the program faster.\n",
    "- *Benchmarking:* Run the program over pairs of arbitrary lists to see how fast it is and how short the solutions are. \n",
    "- *Analyzing:* Learn something by looking at the benchmark results.\n",
    "- *Searching:* Introduce a better search algorithm.\n",
    "- *Eliminating Parts:* Get rid of parts that can't possibly be part of an optimal solution.\n",
    "- *Adding Parts:* Add new types of parts to allow new, shorter solutions.\n",
    "- *Randomizing Search:* Randomness allows us to explore different parts of the search space.\n",
    "- *Speculating:* Think about what we could do next.\n",
    "\n",
    "Profiling \n",
    "----\n",
    "\n",
    "Let's time how long it takes to separate the top 100 adverbs from top 100 nouns:"
   ]
  },
  {
   "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": [
      "1 loops, best of 3: 5.4 s per loop\n"
     ]
    }
   ],
   "source": [
    "%timeit findregex(adverbs, nouns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "On my computer it was 4 seconds.  I have some ideas for how to make this faster, but I know that I shouldn't waste effort trying to speed up parts of a program that [don't take much of the total time](http://en.wikipedia.org/wiki/Amdahl's_law).  I'll use the [`cProfile`](http://docs.python.org/2/library/profile.html#module-cProfile) module to see where the time goes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         12220085 function calls in 7.748 seconds\n",
      "\n",
      "   Ordered by: cumulative time\n",
      "\n",
      "   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
      "        1    0.000    0.000    7.748    7.748 {built-in method builtins.exec}\n",
      "        1    0.000    0.000    7.748    7.748 <string>:1(<module>)\n",
      "        1    0.001    0.001    7.748    7.748 <ipython-input-2-f601ec24f6b0>:23(findregex)\n",
      "    54424    0.051    0.000    7.652    0.000 <ipython-input-2-f601ec24f6b0>:39(matches)\n",
      "    54424    1.052    0.000    7.601    0.000 <ipython-input-2-f601ec24f6b0>:41(<setcomp>)\n",
      "  2841615    1.347    0.000    6.549    0.000 re.py:170(search)\n",
      "  2841615    1.482    0.000    4.016    0.000 re.py:278(_compile)\n",
      "       41    0.015    0.000    3.584    0.087 {built-in method builtins.max}\n",
      "    25445    0.033    0.000    3.569    0.000 <ipython-input-2-f601ec24f6b0>:31(score)\n",
      "       41    0.021    0.001    3.335    0.081 <ipython-input-2-f601ec24f6b0>:36(<setcomp>)\n",
      "    45055    0.223    0.000    2.459    0.000 sre_compile.py:531(compile)\n",
      "    45055    0.169    0.000    1.206    0.000 sre_parse.py:819(parse)\n",
      "  2841615    1.186    0.000    1.186    0.000 {method 'search' of '_sre.SRE_Pattern' objects}\n",
      "    45055    0.080    0.000    0.911    0.000 sre_compile.py:516(_code)\n",
      "        1    0.000    0.000    0.825    0.825 <ipython-input-2-f601ec24f6b0>:46(regex_parts)\n",
      "    45055    0.098    0.000    0.821    0.000 sre_parse.py:429(_parse_sub)\n",
      "        1    0.003    0.003    0.809    0.809 <ipython-input-2-f601ec24f6b0>:50(<setcomp>)\n",
      "    45055    0.281    0.000    0.660    0.000 sre_parse.py:491(_parse)\n",
      "    45055    0.263    0.000    0.650    0.000 sre_compile.py:412(_compile_info)\n",
      "   172941    0.076    0.000    0.246    0.000 sre_parse.py:247(get)\n",
      "   217996    0.212    0.000    0.212    0.000 sre_parse.py:226(__next)\n",
      "    45055    0.159    0.000    0.196    0.000 sre_parse.py:167(getwidth)\n",
      "    45055    0.141    0.000    0.177    0.000 sre_compile.py:64(_compile)\n",
      "   916825    0.129    0.000    0.129    0.000 {method 'append' of 'list' objects}\n",
      "    45055    0.074    0.000    0.122    0.000 sre_parse.py:217(__init__)\n",
      "   172941    0.067    0.000    0.091    0.000 sre_parse.py:165(append)\n",
      "    28890    0.078    0.000    0.082    0.000 sre_compile.py:391(_generate_overlap_table)\n",
      "   574427    0.058    0.000    0.058    0.000 {built-in method builtins.len}\n",
      "    45055    0.046    0.000    0.054    0.000 sre_parse.py:797(fix_flags)\n",
      "    90110    0.040    0.000    0.051    0.000 sre_compile.py:513(isstring)\n",
      "   135163    0.050    0.000    0.050    0.000 {built-in method builtins.min}\n",
      "    45055    0.048    0.000    0.048    0.000 {built-in method _sre.compile}\n",
      "   225275    0.043    0.000    0.043    0.000 {built-in method builtins.isinstance}\n",
      "    90110    0.032    0.000    0.042    0.000 sre_parse.py:75(groups)\n",
      "    45055    0.041    0.000    0.041    0.000 sre_parse.py:70(__init__)\n",
      "    45055    0.026    0.000    0.031    0.000 sre_parse.py:276(tell)\n",
      "    45055    0.029    0.000    0.029    0.000 sre_parse.py:105(__init__)\n",
      "       88    0.020    0.000    0.020    0.000 {method 'clear' of 'dict' objects}\n",
      "    57782    0.017    0.000    0.017    0.000 {method 'extend' of 'list' objects}\n",
      "        1    0.002    0.002    0.016    0.016 <ipython-input-2-f601ec24f6b0>:49(<setcomp>)\n",
      "    45055    0.014    0.000    0.014    0.000 sre_parse.py:242(match)\n",
      "   119455    0.013    0.000    0.013    0.000 {built-in method builtins.ord}\n",
      "     2131    0.005    0.000    0.012    0.000 <ipython-input-2-f601ec24f6b0>:56(dotify)\n",
      "    45055    0.008    0.000    0.008    0.000 {method 'items' of 'dict' objects}\n",
      "     2131    0.004    0.000    0.005    0.000 <ipython-input-2-f601ec24f6b0>:59(<setcomp>)\n",
      "    14684    0.003    0.000    0.003    0.000 {method 'get' of 'dict' objects}\n",
      "    11135    0.002    0.000    0.002    0.000 {method 'join' of 'str' objects}\n",
      "       98    0.001    0.000    0.002    0.000 <ipython-input-2-f601ec24f6b0>:52(subparts)\n",
      "     4921    0.001    0.000    0.001    0.000 <ipython-input-2-f601ec24f6b0>:61(replacements)\n",
      "     2874    0.001    0.000    0.001    0.000 <ipython-input-2-f601ec24f6b0>:54(<genexpr>)\n",
      "        1    0.000    0.000    0.000    0.000 <ipython-input-2-f601ec24f6b0>:48(<setcomp>)\n",
      "        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import cProfile\n",
    "\n",
    "cProfile.run('findregex(adverbs, nouns)', sort='cumulative')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "About 99% of the time was spent in `matches`. And most of the time in `matches` goes to `re.search`. So my thoughts are: \n",
    "    \n",
    "+ Can we make each call to `matches` run faster? \n",
    "+ Can we make fewer calls to `matches`?\n",
    "+ Can we use `re.search` more effectively? \n",
    "+ Nothing else matters.  99% of the time is in `matches`; don't waste effort speeding up anything else.\n",
    "\n",
    "# Speedup:  Faster `matches` by Compiling Regexes\n",
    "\n",
    "\n",
    "The `re` package uses strings to specify regular expressions, but internally, when we call `re.search` on a string, that string is compiled, with the function `re.compile`, into an object that has a `search` method.  If you need to search many times with the same regex, then it is faster to call `re.compile` once, and then call the `search` method of the compiled object, rather than calling `re.search` each time.\n",
    "\n",
    "Another trick: use the builtin function `filter` rather than a set comprehension. Builtins, written in C, are often faster."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def matches(regex, strings):\n",
    "    \"Return a set of all the strings that are matched by regex.\"\n",
    "    searcher = re.compile(regex).search\n",
    "    return set(filter(searcher, strings))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "One thing to be careful about: the `re` module manages a cache of recent compilations. I call `re.purge()` before each timing, to make sure that I'm not re-using any work that was done before the timing started."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 loops, best of 3: 2.95 s per loop\n"
     ]
    }
   ],
   "source": [
    "re.purge()\n",
    "\n",
    "%timeit findregex(adverbs, nouns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "*That was almost twice as fast!*  Not bad for changing two lines.  \n",
    "\n",
    "# Speedup: Fewer `matches` Against Losers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "In `regex_parts`, for each part, `p`, we test `if not matches(p, losers)`. This applies `searcher` to every loser and builds up a set of all those that match.  It would be faster if we could *exit early*: as soon as we find one loser that matches, we don't need to apply `searcher` to the remaining losers.  Stefan Pochmann came up with a great way to do this. If we concatenate the list of losers together into one big string, then we only need one call to `re.search` for each part `p`.  If a part matches the big string anywhere, the call will return immediately, and we will know the part is no good. \n",
    "\n",
    "There is one catch: we have to make sure that the start of each loser matches `'^'` and the end matches `'$'`.  We can do that by concatenating together the losers with a newline between them, and by using the `re.MULTILINE` option. (See the [`re` module documentation](http://docs.python.org/2/library/re.html)  if this is unfamiliar.)\n",
    "\n",
    "Here is the change, with timing before and after:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 loops, best of 3: 271 ms per loop\n"
     ]
    }
   ],
   "source": [
    "re.purge()\n",
    "\n",
    "%timeit regex_parts(adverbs, nouns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def regex_parts(winners, losers):\n",
    "    \"Return parts that match at least one winner, but no loser.\"\n",
    "    losers_str = '\\n'.join(losers)\n",
    "    def no_losers(part): return not re.compile(part, re.MULTILINE).search(losers_str)\n",
    "    wholes = {'^' + w + '$' for w in winners}\n",
    "    parts = {d for w in wholes for p in subparts(w) for d in dotify(p)}\n",
    "    return wholes | set(filter(no_losers, parts))"
   ]
  },
  {
   "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": [
      "10 loops, best of 3: 171 ms per loop\n"
     ]
    }
   ],
   "source": [
    "re.purge()\n",
    "\n",
    "%timeit regex_parts(adverbs, nouns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We've made `regex_parts` almost two times faster.\n",
    "\n",
    "# Speedup: Fewer `matches` Against Winners\n",
    "\n",
    "Here's what `findregex` currently looks like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def findregex(winners, losers, k=4):\n",
    "    \"Find a regex that matches all winners but no losers (sets of strings).\"\n",
    "    # Make a pool of regex parts, then pick from them to cover winners.\n",
    "    # On each iteration, add the 'best' part to 'solution',\n",
    "    # remove winners covered by best, and keep in 'pool' only parts\n",
    "    # that still match some winner.\n",
    "    pool = regex_parts(winners, losers)\n",
    "    solution = []\n",
    "    def score(p): return k * len(matches(p, winners)) - len(p)\n",
    "    while winners:\n",
    "        best = max(pool, key=score)\n",
    "        solution.append(best)\n",
    "        winners = winners - matches(best, winners)\n",
    "        pool = {p for p in pool if matches(p, winners)}\n",
    "    return OR(solution)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Notice that we call `matches` twice (once within `score`) for every part in the pool on every iteration of the main loop. If there are 50 iterations of the loop, and 1000 parts, that's 100,000 calls to `matches`. Instead of repeating all these calls, I propose that, for each part in the pool, we limit ourselves to this:\n",
    "\n",
    "- One `re.compile`.\n",
    "- One `re.search` against each of the winners.\n",
    "- One `re.search` against the big string of losers.\n",
    "- Some cache lookups as needed.\n",
    "\n",
    "During initialization, we create a dict, called `covers`, that will serve as a cache:  `covers[p]` is the set of all winners that match the part `p`. The new function `regex_covers` replaces the old function `regex_parts`. Here is the new `findregex`, with timing before and after:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 loops, best of 3: 2.85 s per loop\n"
     ]
    }
   ],
   "source": [
    "re.purge()\n",
    "\n",
    "%timeit findregex(adverbs, nouns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def findregex(winners, losers, k=4):\n",
    "    \"Find a regex that matches all winners but no losers (sets of strings).\"\n",
    "    # Initialize covers = {regex: {winner,...}} for a large set of regex components.\n",
    "    # On each iteration, add the 'best' component to 'solution',\n",
    "    # remove winners covered by best, and keep in 'pool' only components\n",
    "    # that still match some winner.\n",
    "    covers   = regex_covers(winners, losers)\n",
    "    pool     = list(covers)\n",
    "    solution = []     \n",
    "    def score(p): return k * len(covers[p] & winners) - len(p)\n",
    "    while winners:\n",
    "        best = max(pool, key=score)\n",
    "        solution.append(best)\n",
    "        winners = winners - covers[best]\n",
    "        pool = [p for p in pool \n",
    "                if not covers[p].isdisjoint(winners)]\n",
    "    return OR(solution)\n",
    "\n",
    "def regex_covers(winners, losers):\n",
    "    \"\"\"Generate regex parts and return a dict of {regex: {winner,...}}.\n",
    "    Each regex matches at least one winner and no loser.\"\"\"\n",
    "    losers_str = '\\n'.join(losers)\n",
    "    wholes     = {'^' + w + '$' for w in winners}\n",
    "    parts      = {d for w in wholes for p in subparts(w) for d in dotify(p)}\n",
    "    pool       = wholes | parts\n",
    "    searchers  = {p: re.compile(p, re.MULTILINE).search for p in pool}\n",
    "    return {p: Set(filter(searchers[p], winners)) \n",
    "            for p in pool\n",
    "            if not searchers[p](losers_str)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 loops, best of 3: 251 ms per loop\n"
     ]
    }
   ],
   "source": [
    "re.purge()\n",
    "\n",
    "%timeit findregex(adverbs, nouns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "*Wow!* That's a dozen times faster!  But I don't want to draw too many conclusions from just this one example."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Benchmarking\n",
    "\n",
    "We will benchmark the program on a suite of 22 different problems (11 examples, run in both directions).  The function `benchmark` finds a solution to each problem and prints the number of characters in the solution, and some other information. In the end it prints the total number of characters, and if we use the `%time` magic, we can see how long it took."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "EXAMPLES = [ex for example in [\n",
    "    (winners, 'win', 'lose', losers),\n",
    "    (boys, 'boy', 'girl', girls),\n",
    "    (pharma, 'drug', 'city', cities),\n",
    "    (foo, 'foo', 'bar', bar),\n",
    "    (starwars, 'wars', 'trek', startrek),\n",
    "    (nouns, 'noun', 'adj', adverbs),\n",
    "    (nouns, 'noun', 'verb', verbs),\n",
    "    (randoms, 'rand', 'built', builtins),\n",
    "    (dogs, 'dog', 'cat', cats),\n",
    "    (movies, 'movie', 'tv', tv),\n",
    "    (scientists, 'sci', 'star', stars)]\n",
    "            for ex in (example, example[::-1])] # Do each example both ways\n",
    "\n",
    "SOLUTION = {} # A cached table of solutions; SOLUTION[W, L] will hold a regex\n",
    "               \n",
    "def benchmark(examples=EXAMPLES): \n",
    "    \"Run examples; print summaries; return total of solution lengths.\"\n",
    "    totalchars = 0\n",
    "    for (W, Wname, Lname, L) in examples:\n",
    "        re.purge()\n",
    "        solution = SOLUTION[W, L] = findregex(W, L)\n",
    "        assert not mistakes(solution, W, L)\n",
    "        legend = '{}({}):{}({})'.format(Wname, len(W), Lname, len(L))\n",
    "        print('{:20} {:3}: \"{}\"'.format(legend, len(solution), truncate(solution, 50)))\n",
    "        totalchars += len(solution)\n",
    "    print('Total characters: {:6}'.format(totalchars))\n",
    "    return totalchars\n",
    "\n",
    "def truncate(text, nchars, ellipsis=' ...'):\n",
    "    \"Return whole string, or version truncated to nchars.\"\n",
    "    return text if len(text) < nchars else text[:nchars-len(ellipsis)] + ellipsis"
   ]
  },
  {
   "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": [
      "win(34):lose(34)      54: \"a.a|i..n|j|li|a.t|a..i|bu|oo|ay.|n.e|r.e$|ru|l ...\"\n",
      "lose(34):win(34)      59: \"^d|^s|r.$|^.re|cc|hu|ld.|nd.|l.i|n.y|ya|ss|pa| ...\"\n",
      "boy(10):girl(10)      11: \"e.$|a.$|a.o\"\n",
      "girl(10):boy(10)      10: \"a$|^..i|is\"\n",
      "drug(10):city(10)     15: \"o.$|x|ir|f|q|^e\"\n",
      "city(10):drug(10)     11: \"ri|an|ca|id\"\n",
      "foo(21):bar(21)        3: \"f.o\"\n",
      "bar(21):foo(21)       28: \"r..$|k|.m|^..l|ld|c..n|id|or\"\n",
      "wars(6):trek(9)        9: \" T|E.P|W \"\n",
      "trek(9):wars(6)       15: \"TI|R.. |Y|RA|IS\"\n",
      "noun(100):adj(98)    170: \"m.n|a.e$|m$|in.$|en.$|ch.|^w.r|id|^g|io|s.n|o. ...\"\n",
      "adj(98):noun(100)    155: \"a.l|^..$|st$|et|re$|tl|en$|^al|ver$|nl|^a.o|ui ...\"\n",
      "noun(100):verb(94)   174: \"m.n|er$|am|es|^.ar|ho|.on|or.$|id|f.c|o.l|..h. ...\"\n",
      "verb(94):noun(100)   177: \"^..l|ak|ve$|^..$|s..n|a.n|^fi|^tr|ut$|.pe|o.g| ...\"\n",
      "rand(58):built(147)   76: \"ia|and|^_.e|_s|_.o|.G|e_|P.$|_e|ets|lti|^_.c|^ ...\"\n",
      "built(147):rand(58)  138: \"ro|Wa|as|^d|^i|r..i|li|^o|te.$|a.s$|m..$|up|tr ...\"\n",
      "dog(100):cat(91)      73: \"E.S$|O.S$|DS|.AS|.HI|RD|.D.E|ANS|IES|G.S|N.S$| ...\"\n",
      "cat(91):dog(100)     113: \"AI.$|T$|AN$|EX|A$|L$|Y$|A..B|NX|M.I|H$|R$|R.G| ...\"\n",
      "movie(100):tv(97)    157: \"GO| . |^N|HIN|S O|E IN|A.NI|.A.C|TIO|RIV|U.K|E ...\"\n",
      "tv(97):movie(100)    148: \"H.W|.CI|PR|R..$|D .E|A.ER|O..I|PE|^SE|^RO|T.C| ...\"\n",
      "sci(50):star(50)      70: \"AL..|T..N|R.S|.KA|NN|VE|-|MU|^P|OD|OS|L.O|W.I| ...\"\n",
      "star(50):sci(50)      77: \"CA|T. |LI..|F..D|GR|BU| GA|LO.|R..Y|UM| R| ST| ...\"\n",
      "Total characters:   1743\n",
      "CPU times: user 5.98 s, sys: 19.1 ms, total: 6 s\n",
      "Wall time: 6 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1743"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time benchmark()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "In 5 seconds we solved 22 problems, getting a score of 1749 for the total number of characters in all the solutions.  \n",
    "\n",
    "(**Note:** if you run this, you  might get a slightly different answer.  Why? The algorithm has no random parts in it; shouldn't it return the same result every time? It will return the same results if you run it twice in the same Python.  But when `findregex` evaluates `max(pool, key=score)` and two components are tied for the best score, Python chooses the one that comes first in the iteration of `pool`.  And different versions of Python can iterate over `pool` in different orders.)\n",
    "\n",
    "# Analyzing\n",
    "\n",
    "What can we do to understand the program better?  Let's start by analyzing what the regex parts look like. We cached the solutions in `SOLUTION`, and we can start to examine the solutions and the parts they are made of. For example, how long are the parts that appears in solutions?"
   ]
  },
  {
   "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": [
       "Counter({1: 17, 2: 192, 3: 179, 4: 84, 7: 1, 10: 1})"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "parts   = [p for regex in SOLUTION.values() for p in regex.split('|')]\n",
    "lengths = [len(p) for p in parts]\n",
    "Counter(lengths)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "This says that there are 17 parts of length 1, 198 parts of length 2, etc. There's also one part of length 10; that's such an outlier, I wonder if it is an error? "
   ]
  },
  {
   "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": [
       "'^HAVANESE$'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max(parts, key=len)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "I happen to own [a Havanese](http://pn.smugmug.com/Family/Dobby-Idgie/i-2JPzBkL/A), but I don't think the program knew that.  Rather, the issue is that in the set of `cats` we have `'HAVANA BROWN'` and `'JAVANESE'`, which means that any 4-letter-or-less subsequence of `'HAVANESE'` matches one of these two.  So the only component that doesn't match one of these two cats is the whole, `'^HAVANESE$'`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "\n",
    "\n",
    "What about the individual characters that make up the parts?  Which ones are popular?  We can see:"
   ]
  },
  {
   "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": [
       "[('.', 205),\n",
       " ('$', 71),\n",
       " ('a', 58),\n",
       " ('^', 54),\n",
       " ('e', 48),\n",
       " ('r', 46),\n",
       " ('o', 44),\n",
       " ('t', 37),\n",
       " ('i', 37),\n",
       " ('n', 37),\n",
       " ('l', 35),\n",
       " ('O', 31),\n",
       " ('E', 31),\n",
       " ('A', 30),\n",
       " ('s', 28),\n",
       " ('R', 27),\n",
       " ('S', 26),\n",
       " ('N', 24),\n",
       " ('u', 23),\n",
       " ('I', 23)]"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Counter(cat(parts)).most_common(20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "I wonder if there are parts that appear in many solutions?"
   ]
  },
  {
   "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": [
       "[('id', 4),\n",
       " ('ru', 3),\n",
       " ('hu', 3),\n",
       " ('f.c', 2),\n",
       " ('oo', 2),\n",
       " ('f$', 2),\n",
       " ('lt', 2),\n",
       " ('m.n', 2),\n",
       " ('vi', 2),\n",
       " ('Y', 2),\n",
       " ('^..$', 2),\n",
       " ('N.S$', 2),\n",
       " ('rc', 2),\n",
       " ('^u', 2),\n",
       " ('a$', 2),\n",
       " ('j', 2),\n",
       " ('ls', 2),\n",
       " ('UG', 2),\n",
       " ('^..l', 2),\n",
       " ('YN', 2)]"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Counter(parts).most_common(20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Most parts appear in only 2 solutions or less.\n",
    "\n",
    "# Analyzing: Set Cover Theory\n",
    "\n",
    "Now I want to think about this as a [set cover problem](http://en.wikipedia.org/wiki/Set_cover_problem).  Wikipedia shows this diagram to explain set cover:\n",
    "    \n",
    "<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Simple-bipartite-graph.svg/220px-Simple-bipartite-graph.svg.png\">\n",
    "\n",
    "The idea is that each blue dot in set $u$ on the left represents a regex component, and each green dot in set $v$ represents a winner that is matched by the regex component.  The problem is to pick some blue dots such that all the green dots are covered.  In this example, we can see that picking the blue dots that are second and third  from the top will do it.\n",
    "\n",
    "But in general, what do our graphs look like?  How many blue and green dots are there? How many links between them? Let's build a little tool to find out.  We'll list the $N$ \"most popular\" blue and green dots&mdash;the ones with the most links to the other side.  Then we'll show histograms of all the nodes and their numbers of links.\n",
    "\n",
    "But first some explanation: I use the term *multimap* for a dictionary, like `covers = {regex: {winner,...}}`, that maps keys to collections. Then `invert_multimap(covers)` is of the form `{winner: {regex, ...}}`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def show(W, L, N=10):\n",
    "    \"Summarize the links between the set of winners, W, and its parts.\"\n",
    "    covers = regex_covers(W, L)\n",
    "    inv = invert_multimap(covers)\n",
    "    for ((n1, w), (n2, r)) in zip(top(N, covers), top(N, inv)):\n",
    "        print(\"{:8} {:2} | {:3}| {}\".format(w, n1, n2, r))\n",
    "    print(\"TOTAL %5d | %3d TOTAL\" % (len(covers), len(W)))\n",
    "    plt.subplot(1, 2, 1); histmm(covers, \"parts\", \"winners\")\n",
    "    plt.subplot(1, 2, 2); histmm(inv, \"winners\", \"parts\")\n",
    "    \n",
    "def top(N, multimap): \n",
    "    \"The top N longest items in a dict of {key: {val,...})\"\n",
    "    return sorted([(len(vals), key) for (key, vals) in multimap.items()], reverse=True)[:N]\n",
    "\n",
    "def histmm(multimap, key, val): \n",
    "    \"Display a histogram of how many values each key has.\"\n",
    "    plt.rcParams['figure.figsize'] = (8.0, 4.0)\n",
    "    plt.hist([len(v) for v in multimap.values()])\n",
    "    plt.xlabel('set size of {' + val + ',...}')\n",
    "    plt.ylabel('number of ' + key + ' mapping to that size')\n",
    "\n",
    "def invert_multimap(multimap):\n",
    "    \"Covert {key: {val,...}} to {val: [key,...]}.\"\n",
    "    result = defaultdict(set)\n",
    "    for key in multimap:\n",
    "        for val in multimap[key]:\n",
    "            result[val].add(key)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "i..n      4 | 110| van-buren\n",
      "a.a       4 |  98| washington\n",
      "a..i      4 |  93| jefferson\n",
      "r.i.      3 |  93| eisenhower\n",
      "r.i       3 |  81| garfield\n",
      "oo..      3 |  78| roosevelt\n",
      "oo.       3 |  72| buchanan\n",
      "oo        3 |  61| obama\n",
      "ma        3 |  61| kennedy\n",
      "li..      3 |  59| jackson\n",
      "TOTAL  1615 |  34 TOTAL\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZAAAAEPCAYAAABsj5JaAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XmYHVWd//H3h7AGCAQXBBoMYkAyArJIUGBoHGQYFVBQ\nFgXZRBlU8KciCSpkdAYBRVkcNyRhEaKICGGESGBoxUEIZoFASAQhCigBVPYACfn8/jink5u2u2/d\npfr27f6+nqeerlu36tT3Vte9p+qcU+fINiGEEEKtVmt1ACGEENpTZCAhhBDqEhlICCGEukQGEkII\noS6RgYQQQqhLZCAhhBDqUloGImmypMWS5vVY/mlJ90u6V9LZFcsnSnpA0gJJ+1Ys31nSvPze+WXF\nG0Ir5PP+vnyOXylprVbHFEJRZd6BTAH2q1wgaW/gAGB7228FvpGXjwMOBcblbb4jSXmz7wLH2R4L\njJW0SpohtCtJY4DjgZ1sbweMAA5rZUwh1KK0DMT2bcDfeyz+d+BrtpfmdZ7Myw8EptpeansR8CAw\nXtImwPq2Z+b1LgPeX1bMIQywZ4GlwEhJqwMjgcdaG1IIxQ10HchY4J8l3SGpS9IuefmmwKMV6z0K\nbNbL8sfy8hDanu2/AecCfwL+DDxt++bWRhVCcQOdgawOjLa9G3AKcNUA7z+EQUPSVsBngDGki6X1\nJH2kpUGFUIPVB3h/jwLXANi+S9JySa8l3VlsXrFeR173sTxfubzXW3xJ0alXKJVtVV+rJrsAt9v+\nK4Cka4B3Ald0rxDndRgI9Z7bA30Hci3wLgBJWwNr2n4KmAYcJmlNSVuSirpm2n4ceFbS+FypfmRO\no1e2mz6dccYZbZFmpFturCVZAOwmaZ18fu8DzG/meZ2cAbiOaeW+az2uOfIeU9E4+v7Mzfj/RhrN\nO7dLuwORN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+kX3xrl1Y/fAUP8h\naf8e+9oQeKCvzzVotLoSZjBNpCKXu0lflpnkikJSWeSvWDm2wXF5+UH0UolOugK/jXTCzwO+kJcf\nBVxAOrFeZWUl+hzSncrawPfydveSx2LoJc5zWFmJ/qGK5c9W+XxTqKhEz8veRbp76G6FshD4TMX7\nD7GyEv2eiuWfA07P8ysqVYHXAg/leQH/VXEcbiFluCvGmahy3K8Hxuf5yrE+dgEuqth+To/PNAaY\n1+rzKabBMZFKAv694vWAnB/5e/rWOrZT/r5s0+pjV22K8UCGEUn/Ddxr+7utjqUISdO9anFh0e12\nBS6wvVvVlcOQJ2k86cLtXtvH5YYc05zqOQYVSduQirbnAUc53UENWpGBDCM9v0itjqcMkj4PfAT4\nuu0rWx1PCENZZCAhhBDqEpXoIYQQ6hIZSAghhLpEBhJCCKEukYGEEEKoS2QgIYQQ6vL/AQ7HX7y7\ntaKdAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x102c669e8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "show(winners, losers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "What does this say?  First the table says that there are only three regexes that have 4 winners; all the rest have 3 or fewer winners.  So the links going left-to-right are rather sparse.  There are more links going the other direction; 110 to `van-buren`, for example.  The histograms give the whole picture mapping set sizes to the number of keys that have that set size.  So, on the left we see that over 1400 regexes have a set size of one winner, and 100 or fewer have set sizes of 2 and 3, and we saw that only 3 regexes have a set size of 4 winners.  On the right, the histogram shows a wide spread of winners that have set sizes between 1 and 110 regexes.\n",
    "\n",
    "From looking at this I get two ideas:\n",
    "    \n",
    "+ I notice that both `'oo..'` and `'oo.'` happen to match 3 winners. But even if I didn't know how many they matched, I would know that the winners matched by `'oo..'` must be a subset of the winners matched by `'oo.'` (remember that a set is a subset of itself). Furthermore, `'oo.'` is shorter.  This suggests that we would *never* want to use  `'oo..'` in a solution, because we could always make the solution one character shorter (and cover at least all the same winners) by substituting `'oo.'`.  We say that * part A dominates B* if *A* is shorter and matches a superset of winners. We might as well throw out all dominated parts right at the start.\n",
    "\n",
    "+ It might be a good idea to pay special attention to the characters, like `'-'`, that appear in the winners but not the losers.\n",
    "\n",
    "Let's look at another example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E.S$     41 | 186| SOFT COATED WHEATEN TERRIERS\n",
      "RS$      34 | 184| STAFFORDSHIRE BULL TERRIERS\n",
      "ERS$     34 | 175| GREATER SWISS MOUNTAIN DOGS\n",
      ".RS$     34 | 162| TREEING WALKER COONHOUNDS\n",
      "IE.S     22 | 157| CAVALIER KING CHARLES SPANIELS\n",
      "E.RI     21 | 149| AMERICAN STAFFORDSHIRE TERRIERS\n",
      "T..R     20 | 147| WEST HIGHLAND WHITE TERRIERS\n",
      "IER.     19 | 146| STANDARD SCHNAUZERS\n",
      "IER      19 | 146| FLAT-COATED RETRIEVERS\n",
      "I.R.     19 | 146| CHESAPEAKE BAY RETRIEVERS\n",
      "TOTAL  4570 | 100 TOTAL\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAgAAAAEPCAYAAAA0xnyyAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XmcHVWd///Xm0AgbCJflTVMUCMaBUGQqMDY+BVEkUVQ\nFpVFIqJRwXVY5oskMtMCyu6ACzsKigsYBoQEhmaaH0IkJCQQERgJSAYCLhh2EvL5/XHOJUVzu7u6\nb92+t7vfz8fjPrrqVNWpT3V31T1VdRZFBGZmZja6rNLqAMzMzGzouQBgZmY2CrkAYGZmNgq5AGBm\nZj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lvAf+WC8QfB06WVKuj8968/kXAD+pUAhwDXJofn98JnBkR/yB9qYakzUiv\nyg4rVAR8F3AisFqu3Hc3ML1ngBFxJSuHyb2RNMz147XFvR1YRKwgDTu7fo9FfwS+KGkh6Zp0bo71\nx6R6PdeR6vG8IrvC9M+Ab0qaQxrPvudxLwU2I91oIGljSdfUNlaqdLlhnp4uaY8e+1oPuL+34xpV\nWl0JYTR+SI+s7yKd+LPJlX5I76VuZuV44lNy+j7UqQRIugPuJp28C4B/yemHAGeRTpKXWFkJcC7p\nScEawA/ydneTx4ivE+cprKwE+IlC+tJ+ju9CCpUAc9oHSHfv4/L8H4GvFJb/iZWVAOcX0r8OfCtP\nv1xBCngd8Kc8LeDfC7+HG0kFpvcXj62P3/vVwOQ8fQRwRJ7eDvhxYfu5PY5pArCg1f9P/vjTqg/p\n6eMXCvNDck7ka9M7BrGd8jVii1b/7trho/xLMauMpP8A7o6Ic1sdSxmSrotXvm4pu932wFkR8Z5+\nVzYbgSRNJt1s3B0RU3Ll2xmR3vO3FUlbkF6HLgAOifQEY1RzAcAq1/Oi0Op4mkHSN4BPAd+NiMta\nHY+Z2UC5AGBmZjYKuRKgmZnZKOQCgJmZ2SjkAoCZmdko5AKAmZnZKOQCgJmZ2Sj0/wPiR0FbftVR\n2wAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x102da1a90>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "show(dogs, cats)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "My immediate reaction to this is \"there are a lot of retrievers and terriers.\"  All ten of the parts in the table recognize this fact, but the left-hand histogram shows that almost all the parts match fewer than 5 dog breeds. In contrast, the right-hand histogram shows that most of the dog breeds have 9 or more parts that match them.\n",
    "\n",
    "Let's look at one more example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a.l      12 |  94| especially\n",
      "a.ly     11 |  83| eventually\n",
      "a.l.     11 |  74| particularly\n",
      ".a.l     11 |  67| actually\n",
      "ll        9 |  65| quickly\n",
      "^..$      9 |  65| exactly\n",
      ".ll       9 |  65| directly\n",
      "..ll      8 |  63| certainly\n",
      "all       7 |  61| usually\n",
      "st$       6 |  57| recently\n",
      "TOTAL  2049 |  98 TOTAL\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAgAAAAEPCAYAAAA0xnyyAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XuYJVV97vHv64DcLxKROw4iGFEQBAEVY2MUSQigoBC8\ngRKEgwomagRzlBlJUCQgohEVuSsYQIUhcpCBQxM8qMgwwMCIgjIqowxoRJDrDLznj1rN7Gl6d9dM\n7921e/f7eZ56umrVrtq/3d2r9qpV6yLbRERExNTynKYDiIiIiImXAkBERMQUlAJARETEFJQCQERE\nxBSUAkBERMQUlAJARETEFNS1AoCkzSRdK+kOSbdLOqqkrydptqSfS7pK0rotxxwr6S5Jd0raoyV9\nR0nzyr4vdCvmiOgMSatK+rGkWyTNl/SZkt42/0fExOpmDcBi4B9tvwzYFfiApJcCxwCzbW8NXFO2\nkbQNcCCwDbAn8GVJKuc6HTjU9lbAVpL27GLcETFOth8Hdre9PbAdsLuk3WiT/yNi4nWtAGD7Ptu3\nlPU/Az8FNgH2Ac4tLzsXeEtZ3xe40PZi2wuAu4FdJG0ErGX7xvK681qOiYgeZfvRsvpcYBrwR9rn\n/4iYYBPSBkDSdGAH4MfABrYXlV2LgA3K+sbAvS2H3UtVYBievrCkR0QPk/QcSbdQ5fNrbd9B+/wf\nEROs6wUASWsC3waOtv1w6z5X4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CgANmKIXhuupMt91\nZf0Iqrv4OsYqfHwfOHKooZ+krYc/0ijpI/3ekfQZSW+pGUvr+Z4HHABsYnv28h4ffW9b4MelZupT\nwL+WwvDbgBMlDbXPeXV5/TnAV0ZoBDgNOL9Un98MfMH2n6i+VC1pc6rHZO9raQj4SuB4YOXSuO92\nYObwAG1/l6pm7Faq5+MfKzV+0P6mA9tPU007u96wXT8DPiBpPtX16PQS6xlUbXqupGrDs8zpWta/\nBXxM0hyq+eyHf+6HgM2pbjKQtLGk7w0drKrR5YZlfaakvYe917pU02EHpBFgEwtVlfWtVJn/RkrD\nH6pnU9dRNVK7HTi0pO/HCI0Aqe6Ar6fKwPOAfy7pBwOnUWWUp1jaCHAuVU3BqsBXynG3U+YPHyHO\nz7G0EeDbW9IfGuPznU1LI8CS9gaqu/fVyvbPgA+37P8lSxsB3taS/hHgU2X9mUZSwPOBX5Z1Af/W\n8nu4hqrA9Mzc6GP83i8HdinrhwOHl/WdgDNajp877DNNB+Y1/f+UJUsTC1XN4/9q2Z6Q/FCuSy9f\ngeNUrg8vafp31yuLyi8momMk/Qdwu+3Tm46lDklXetnHLXWP2xk4zfauY744os9I2oXqRuN224eW\nhrezXD3n7ymSXkL1KHQecLCrGowpLwWA6LjhF4am4+kGSR8F3gmcZPuCpuOJiFheKQBERERMQWkE\nGBERMQWlABARETEFpQAQERExBaUAEBERMQWlABARETEF/X/aFFVT5yLBAAAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1014dbb38>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "show(adverbs, nouns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "The pattern looks similar here.  Almost all the parts match only one winner, but most of the winners are matched by many parts. What can I conclude from this?\n",
    "\n",
    "+ It would be good to think of new types of parts that match more winners.\n",
    "+ Most parts are 2 or 3 characters long and most match just 1 or 2 winners.  That suggests that often we will have a tie in the `score` function, and greedy search will arbitrarily pick the one that comes first. But I'm worried that another choice might be better. Maybe we should replace greedy search with something that considers more than one choice.\n",
    "\n",
    "Given all we've seen, I will shift my attention to understanding the search algorithm we have, and thinking about how to improve it."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Analyzing: Understanding Greedy vs. Exhaustive Search\n",
    "\n",
    "`findregex` is a *greedy search* algorithm. In general, greedy search is used when you are trying to find a solution that is composed of parts.  On each iteration you choose a part that looks good, and you never reconsider that choice;  you just keep on adding parts until you get a complete solution.   \n",
    "\n",
    "The pseudo-code for a general `greedy_search`, described as a recursive function, is given below. It takes two arguments: a set of parts, and a partial solution indicating parts that have previously been chosen.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "# Pseudocode \n",
    "def greedy_search(parts, partial_solution=None):\n",
    "    if is_complete(partial_solution):\n",
    "        return partial_solution\n",
    "    else:\n",
    "        best = max(parts, key=score)\n",
    "        return greedy_search(parts - {best}, partial_solution + best)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "An *exhaustive search* considers *every* possible choice of parts, and selects the best solution.  On each iteration exhaustive search picks a part (just like greedy search), but then it considers *both* using the part and not using the part. You can see that exhaustive search is almost identical to greedy search, except that it has *two* recursive calls (on lines 7 and 8) instead of *one* (on line 7).  (*If you are viewing this in a iPython notebook, not just a web page, you can toggle line numbers by pressing 'ctrl-M L' within a cell.*) How do we choose between the results of the two calls?  We need a cost function that we are trying to minimize. (For regex golf the cost of a solution is the length of the string.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "# Pseudocode\n",
    "def exhaustive_search(parts, partial_solution=None):\n",
    "    if is_complete(partial_solution):\n",
    "        return partial_solution\n",
    "    else:\n",
    "        best = max(parts, key=score)\n",
    "        return min(exhaustive_search(parts - {best}, partial_solution + best),\n",
    "                   exhaustive_search(parts - {best}, partial_solution),\n",
    "                   key=cost)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Here's an interesting piece of trivia: the first thing that exhaustive search does is a greedy search!  Think about it: on each recursive call, `exhaustive_search` selects the best part, and then calls itself recursively with `best` chosen as part of the partial solution.  It keeps going until it reaches a complete solution.  That's exactly what greedy search does. But then exhaustive search does more:  It also considers all the cases where it *didn't* choose the best part.\n",
    "\n",
    "Here's something else to ponder: why should we bother with selecting the \"best\" part?  If we're going to explore *all* possibilities, wouldn't it be the same if we just selected *any* part, not the \"best\" one?\n",
    "\n",
    "# Searching: Computational Complexity of Greedy and Exhaustive Search\n",
    "\n",
    "\n",
    "Greedy search only considers one path towards the goal of finding a solution. Exhaustive search considers two paths on *every* iteration.  How much work is that all together? If there are *P* parts, then there are $2^P$ subsets of parts. Now, we don't have to consider every one of these subsets, because the search ends when we cover all the winners.  If there are $W$ winners, than an upper bound on the number of combinations we have to consider is the number of ways we can pick $W$ parts from a pool of $P$, which in math we write as  ($P$ choose $W$).  For the presidential candidates  $W$, is 34, and $P$ is 1615.\n",
    "\n",
    "So exhaustive search would have to consider roughly [(1615 choose 34)](https://www.google.com/search?q=1615+choose+34) = $10^{70}$ combinations, which is clearly too many. Don't even think about dogs versus cats, where $W$ = 100 and $P$ = 4570, so [(4570 choose  100)](https://www.google.com/search?q=4570+choose+100) = $10^{207}$. Fortunately, there is another way.\n",
    "\n",
    "# Searching: Branch and Bound Search\n",
    "\n",
    "[*Branch and bound*](http://en.wikipedia.org/wiki/Branch_and_bound) is a search strategy that gets the same answer as exhaustive search, but runs faster because it avoids considering many combinations that could not possibly lead to an optimal solution.  Here's how and why it works:\n",
    "\n",
    "- The *branch* part of the name means that, just like exhaustive search, on each iteration it picks a part, and considers two branches, one where the part is in the solution, and one where it is not.  \n",
    "- The *bound* part of the name means that the algorithm continually keeps track of the lowest-cost solution it has found so far.  This serves as a *bound* on what the optimal solution can be.\n",
    "- The *trick* is to notice that the cost of a partial solution always *increases* as we add more parts to it.  Therefore, if we ever get to a partial solution whose cost is more than the lowest-cost solution we have found so far, then we can *immediately* discard the partial solution, and *never consider* all the other combinations that would have come from continuing the partial solution. If there are $MP$ parts left to consider, that means we just eliminated $2^P$ potential combinations all at once. \"Eliminating potential combinations\" is also called \"pruning the search tree\"&mdash;\"[pruning](https://www.google.com/search?q=pruning)\" means cutting off unwanted branches.\n",
    "\n",
    "The pseudocode below uses a global variable called `CHEAPEST` to hold the lowest-cost solution found so far.  Note that the two branches (two recursive calls in lines 7 and 8) communicate through this global variable.  If the first branch sets `CHEAPEST` to an improved solution, then the second branch will see it.  That is why it is important to choose good \"best\" parts&mdash;it means we are more likely to find a good solution early on, which makes it more likely that we can prune away branches.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "# Pseudocode\n",
    "def branch_and_bound_search(parts, partial_solution=None):\n",
    "    if is_complete(partial_solution):\n",
    "        CHEAPEST = min(CHEAPEST, partial_solution, key=cost)\n",
    "    elif cost(partial_solution) < cost(CHEAPEST):\n",
    "        best = select_best(parts)\n",
    "        branch_and_bound_search(parts - {best}, partial_solution + best)\n",
    "        branch_and_bound_search(parts - {best}, partial_solution)\n",
    "    return CHEAPEST"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "\n",
    "\n",
    "# Searching: Anytime Branch and Bound Search\n",
    "\n",
    "Even with all this pruning, we still may be presented with problems that require trillions of recursive calls.  [Who's got that kind of time?](http://www.gocomics.com/calvinandhobbes/1995/08/17#.UvSJImSwI8g)  But if we stop the algorithm at any time, we still have our best solution stored in `CHEAPEST`. Algorithms that have the property that an answer is always available are called [*anytime algorithms*](http://en.wikipedia.org/wiki/Anytime_algorithm); let's do that.\n",
    "\n",
    "I can think of two easy ways to allow early stopping.  We could use the [`threading.Timer`](http://docs.python.org/2/library/threading.html#timer-objects) class to  run the search for a given number of seconds, then stop.  Or we could have a counter which gets decremented every time we make a call, and when it hits zero, stop.  I'll use the second approach.\n",
    "\n",
    "Enough pseudocode&mdash;here is a real implementation.  Since global variables are [considered bad style](https://google.github.io/styleguide/pyguide.html#Global_variables), I decided to use a class, `BranchBound`, to hold the lowest-cost solution and the number of calls remaining.  The class provides one method, `search`, which does the work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "class BranchBound(object):\n",
    "    \"Hold state information for a branch and bound search.\"\n",
    "    def __init__(self, winners, max_num_calls, k=4):\n",
    "        self.cheapest = trivial(winners)\n",
    "        self.calls    = max_num_calls\n",
    "        self.k        = k\n",
    "        \n",
    "    def search(self, covers, partial=None):\n",
    "        \"\"\"Recursively extend partial regex until it matches all winners in covers.\n",
    "        Try all reasonable combinations until we run out of calls.\"\"\"\n",
    "        if self.calls <= 0: \n",
    "            return self.cheapest\n",
    "        self.calls -= 1\n",
    "        covers, partial = simplify_covers(covers, partial)\n",
    "        if not covers: # Nothing left to cover; solution is complete\n",
    "            self.cheapest = min(partial, self.cheapest, key=len)\n",
    "        elif len(OR(partial, min(covers, key=len))) < len(self.cheapest):\n",
    "            def score(p): return self.k * len(covers[p]) - len(p)\n",
    "            best = max(covers, key=score) # Best part\n",
    "            covered = covers[best] # Set of winners covered by best\n",
    "            covers.pop(best)\n",
    "            # Try with and without the greedy-best part\n",
    "            self.search({c:covers[c]-covered for c in covers}, OR(partial, best))\n",
    "            self.search(covers, partial)\n",
    "        return self.cheapest"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Simplifying Covers\n",
    "\n",
    "There's a new function introduced above, `simplify_covers`.  The idea is that you pass it a `covers` dict and a partial regex, and it does a triage process to divide the components in `covers` into three categories:\n",
    "\n",
    "- *Useless components*: could never appear in an optimal solution.\n",
    "- *Necessary components*: must appear in any solution (because no other component covers some winner).\n",
    "- *Remaining components*: neither useless nor necessary.\n",
    "    \n",
    "The necessary components are joined to the partial regex that is passed in, to yield a new partial regex that the function returns.  The useless components are eliminated, and the remaining ones are returned in a new `covers` dict.  \n",
    "\n",
    "`simplify_covers` works by first eliminating useless components, and then selecting necessary components.  We keep repeating this process of eliminating and selecting until there are no more changes to `covers`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def simplify_covers(covers, partial=None):\n",
    "    \"Eliminate dominated regexes, and select ones that uniquely cover a winner.\"\n",
    "    previous = None\n",
    "    while covers != previous:\n",
    "        previous = covers\n",
    "        covers = eliminate_dominated(covers)\n",
    "        covers, necessary = select_necessary(covers)\n",
    "        partial = OR(partial, necessary)\n",
    "    return covers, partial"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "For convenience we modified the function `OR` slightly; we made it work just like the function `max` in that you can call it two ways: either with a single argument, which is a collection of components, or with 2 or more arguments, each a component. We also made it ignore components that are `None`, so that `OR(None, 'a')` equals `'a'`, but `OR('a', 'b')` equals `'a|b'`, as does `OR(['a', 'b'])`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def OR(*regexes):\n",
    "    \"\"\"OR together component regexes. Ignore 'None' components.\n",
    "    Allows both OR(a, b, c) and OR([a, b, c]), similar to max.\"\"\"\n",
    "    if len(regexes) == 1: \n",
    "        regexes = regexes[0]\n",
    "    return '|'.join(r for r in regexes if r)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Simplifying Covers: Eliminating Dominated Components\n",
    "\n",
    "We defined the notion of a regex being *dominated* if there is some other regex that is shorter (or at least not longer) and covers a superset of winners. How can we efficiently compute which parts are dominated? Here's one simple approach: go through each regex part, `p`, and every time we find one that is not dominated by any another regex part `p2`, add `p` (and its winners) to a new dict that we are building up.  This approach works, but it is $O(n^2)$.\n",
    "\n",
    "Here's an alternative that is faster: First, sort all the regexes so that the ones that match more winners come first (in case of tie, put the shorter ones first).  (In other words, \"best\" first.)   Initialize a new dict to empty, and go through the sorted regexes, `p`, one at a time.  For each `p`, compare it only to the regexes, `p2`, that we have already added to the new dict; if none of them dominate `p`, then add `p`. This is still $O(n^2)$, but if, say, 99 out of 100 regexes are eliminated, we will only need $n^2/100$ comparisons.\n",
    "\n",
    "The code for `eliminate_dominated` is a slight variant on the [version](https://github.com/pochmann/regex-golf) by Stefan Pochmann (because his version turned out to be better than my first version). Note that the function `signature` represents a regex as a pair of numbers, the negative of the number of winners and the length in characters.  The smaller (in lexicographical order) this pair is, the \"better\" the regex is.  Why is it important to put the regexes in sorted order?  So that we know that the only possible dominators are the ones that came *before*, not ones that come after. Note that, as we are going through the component regexes, `p`, in sorted order, if we ever hit a `p` that covers no winners, then we know that all the remaining `p` will also cover no winners (because we're going in best-first order), so we can break out of the loop immediately. And one more thing: the expression `covers[p2] >= covers[p]` asks if `p2` covers a superset of the winners that `p` covers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def eliminate_dominated(covers):\n",
    "    \"\"\"Given a dict of {regex: {winner...}}, make a new dict with only the regexes\n",
    "    that are not dominated by any others. A regex part p is dominated by p2 if p2 covers \n",
    "    a superset of the matches covered by p, and rp is shorter.\"\"\"\n",
    "    newcovers = {}\n",
    "    def signature(p): return (-len(covers[p]), len(p))\n",
    "    for p in sorted(covers, key=signature):\n",
    "        if not covers[p]: break # All remaining r must not cover anything\n",
    "        # r goes in newcache if it is not dominated by any other regex\n",
    "        if not any(covers[p2] >= covers[p] and len(p2) <= len(p) \n",
    "                   for p2 in newcovers):\n",
    "            newcovers[p] = covers[p]\n",
    "    return newcovers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Simplifying Covers: Selecting Necessary Components\n",
    "\n",
    "\n",
    "If some winner is covered by only one part, then we know that part must be part of the solution.  The function `select_necessary` finds all such parts, `OR`s them together, and returns that, along with a dict of the remaining covers, after removing the necessary parts (and removing all the winners that are covered by the neccessary parts)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def select_necessary(covers):\n",
    "    \"\"\"Select winners covered by only one part; remove from covers.\n",
    "    Return a pair of (covers, necessary).\"\"\"\n",
    "    counts = Counter(w for p in covers for w in covers[p])\n",
    "    necessary = {p for p in covers if any(counts[w] == 1 for w in covers[p])}\n",
    "    if necessary:\n",
    "        covered = {w for p in necessary for w in covers[p]}\n",
    "        covers = {p: covers[p] - covered \n",
    "                  for p in covers if p not in necessary}\n",
    "        return covers, OR(necessary)\n",
    "    else:\n",
    "        return covers, None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Testing and Benchmarking: Branch and Bound\n",
    "\n",
    "Let's make up a test suite (showing some examples of how these functions work).  Then let's see if `findregex` works with the new branch and bound search. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'test_bb passes'"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def test_bb():\n",
    "    assert OR(['a', 'b', 'c']) == OR('a', 'b', 'c') == 'a|b|c'\n",
    "    assert OR(['a|b', 'c|d']) == OR('a|b', 'c|d') == 'a|b|c|d'\n",
    "    assert OR(None, 'c') == 'c'\n",
    "    covers1 = {'a': {'ann', 'abe'}, 'ab': {'abe'}}\n",
    "    assert eliminate_dominated(covers1) == {'a': {'ann', 'abe'}}\n",
    "    assert simplify_covers(covers1) == ({}, 'a')\n",
    "    covers2 = {'a': {'abe', 'cab'}, 'b': {'abe', 'cab', 'bee'}, \n",
    "               'c': {'cab', 'cee'}, 'c.': {'cab', 'cee'}, 'abe': {'abe'},\n",
    "               'ab': {'abe', 'cab'}, '.*b': {'abe', 'cab', 'bee'}, \n",
    "               'e': {'abe', 'bee', 'cee'}, 'f': {}, 'g': {}}\n",
    "    assert eliminate_dominated(covers2) == simplify_covers(covers2)[0] == {\n",
    "        'c': {'cab', 'cee'}, 'b': {'cab', 'abe', 'bee'}, 'e': {'cee', 'abe', 'bee'}}\n",
    "    covers3 = {'1': {'w1'}, '.1': {'w1'}, '2': {'w2'}}\n",
    "    assert eliminate_dominated(covers3) == {'1': {'w1'}, '2': {'w2'}}\n",
    "    assert simplify_covers(covers3) in (({}, '2|1'), ({}, '1|2'))\n",
    "    covers, nec = select_necessary({'a': {'abe'}, 'c': {'cee'}})\n",
    "    assert covers == {} and (nec == 'c|a' or nec == 'a|c')\n",
    "    assert {0, 1, 2} >= {1, 2}\n",
    "    assert {1, 2} >= {1, 2}\n",
    "    assert not ({1, 2, 4} >= {1, 3})\n",
    "    return 'test_bb passes'\n",
    "\n",
    "test_bb()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Let's investigate how much the cover simplification process is helping:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1615"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "covers = regex_covers(winners, losers)\n",
    "len(covers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "49"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "covers2, partial = simplify_covers(covers)\n",
    "len(covers2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9696594427244583"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1 - len(covers2)/len(covers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We see that `simplify_covers` gives us a 97% reduction in the number of parts! What do the remaining covers look like?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({'-': frozenset({'van-buren'}),\n",
       "  '.b': frozenset({'obama', 'van-buren'}),\n",
       "  '.f': frozenset({'garfield', 'taft'}),\n",
       "  '.h.n': frozenset({'buchanan', 'washington'}),\n",
       "  '.se': frozenset({'eisenhower', 'roosevelt'}),\n",
       "  'a..i': frozenset({'garfield', 'harding', 'harrison', 'washington'}),\n",
       "  'a.a': frozenset({'adams', 'buchanan', 'obama', 'reagan'}),\n",
       "  'a.t': frozenset({'carter', 'grant', 'taft'}),\n",
       "  'ad': frozenset({'adams', 'madison'}),\n",
       "  'am': frozenset({'adams', 'obama'}),\n",
       "  'an.$': frozenset({'cleveland', 'grant'}),\n",
       "  'ay.': frozenset({'hayes', 'taylor'}),\n",
       "  'bu': frozenset({'buchanan', 'bush', 'van-buren'}),\n",
       "  'di': frozenset({'harding', 'madison'}),\n",
       "  'ed': frozenset({'kennedy'}),\n",
       "  'el.$': frozenset({'garfield', 'roosevelt'}),\n",
       "  'g..n': frozenset({'grant', 'washington'}),\n",
       "  'ga': frozenset({'garfield', 'reagan'}),\n",
       "  'h..e': frozenset({'eisenhower', 'hayes'}),\n",
       "  'ho': frozenset({'eisenhower', 'hoover'}),\n",
       "  'i..n': frozenset({'eisenhower', 'harrison', 'madison', 'nixon'}),\n",
       "  'i..o': frozenset({'clinton', 'lincoln', 'wilson'}),\n",
       "  'i.l': frozenset({'garfield', 'mckinley'}),\n",
       "  'i.o': frozenset({'harrison', 'madison', 'nixon'}),\n",
       "  'ie.': frozenset({'garfield', 'pierce'}),\n",
       "  'is.': frozenset({'eisenhower', 'harrison', 'madison'}),\n",
       "  'li': frozenset({'clinton', 'coolidge', 'lincoln'}),\n",
       "  'ls': frozenset({'wilson'}),\n",
       "  'm..i': frozenset({'madison', 'mckinley'}),\n",
       "  'ma': frozenset({'madison', 'obama', 'truman'}),\n",
       "  'n..o': frozenset({'nixon', 'washington'}),\n",
       "  'n.e': frozenset({'kennedy', 'mckinley'}),\n",
       "  'nl': frozenset({'mckinley'}),\n",
       "  'oe': frozenset({'monroe'}),\n",
       "  'oo': frozenset({'coolidge', 'hoover', 'roosevelt'}),\n",
       "  'r..s': frozenset({'harrison', 'roosevelt'}),\n",
       "  'r.e$': frozenset({'monroe', 'pierce'}),\n",
       "  'r.i': frozenset({'garfield', 'harding', 'harrison'}),\n",
       "  'r.n': frozenset({'grant', 'van-buren'}),\n",
       "  'ra': frozenset({'grant'}),\n",
       "  'rc': frozenset({'pierce'}),\n",
       "  'rt': frozenset({'carter'}),\n",
       "  'sh': frozenset({'bush', 'washington'}),\n",
       "  'ta': frozenset({'taft', 'taylor'}),\n",
       "  'to': frozenset({'clinton', 'washington'}),\n",
       "  'u..n': frozenset({'truman', 'van-buren'}),\n",
       "  'vel': frozenset({'cleveland', 'roosevelt'}),\n",
       "  'xo': frozenset({'nixon'}),\n",
       "  'ye': frozenset({'hayes'})},\n",
       " 'j|po')"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "simplify_covers(covers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    " Now let's benchmark  branch and bound.  I'm going to introduce a modified version of `benchmark`, called `bbenchmark`, to print the number of calls taken. The easiest way to do that is to introduce a new version of `findregex`, called `bb_findregex`, that returns the `BranchBound` object it creates, rather than returning the solution. (In general, I tend to introduce a new function when I change the call/return signature, but not when I just improve the mechanism.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def bbenchmark(examples=EXAMPLES, calls=10**4): \n",
    "    \"Run these data sets; print summaries; return total of solution lengths.\"\n",
    "    totalchars = 0\n",
    "    for (W, Wname, Lname, L) in examples: # Do both ways\n",
    "        re.purge()\n",
    "        bb = bb_findregex(W, L, calls)\n",
    "        SOLUTION[W, L] = bb.cheapest\n",
    "        assert not mistakes(bb.cheapest, W, L)\n",
    "        legend = '{}({}):{}({})'.format(Wname, len(W), Lname, len(L))\n",
    "        print('{:20} {:6} calls, {:3}: \"{}\"'.format(\n",
    "              legend, (calls - bb.calls), len(bb.cheapest),  truncate(bb.cheapest, 45)))\n",
    "        totalchars += len(bb.cheapest)\n",
    "    return totalchars\n",
    "\n",
    "def bb_findregex(winners, losers, calls=10**4):\n",
    "    \"Return a BranchBound object which contains the shortest regex that covers winners but not losers.\"\n",
    "    bb = BranchBound(winners, calls)\n",
    "    bb.search(regex_covers(winners, losers))\n",
    "    return bb\n",
    "\n",
    "def findregex(winners, losers): return bb_findregex(winners, losers).cheapest"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Remember, the old benchmark took about 5 seconds and totaled 1749 characters. Let's see how the branch and bound benchmark compares:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "win(34):lose(34)       1000 calls,  52: \"j|po|a.a|a..i|bu|ma|li|ls|a.t|vel|ho|xo|a ...\"\n",
      "lose(34):win(34)       1000 calls,  58: \"^s|ox|ss|^ki|^d|go|^.re|hu|ry|ai|k..$|n.y ...\"\n",
      "boy(10):girl(10)          9 calls,  11: \"de|a.$|c|as\"\n",
      "girl(10):boy(10)         13 calls,  10: \"a$|a.i|e.i\"\n",
      "drug(10):city(10)         3 calls,  15: \"ir|^e|o.$|f|x|q\"\n",
      "city(10):drug(10)        17 calls,  11: \"ri|an|h|a.e\"\n",
      "foo(21):bar(21)           1 calls,   3: \"f.o\"\n",
      "bar(21):foo(21)         205 calls,  24: \"k|ld|b|...n|ah|ar|or|z|A\"\n",
      "wars(6):trek(9)          21 calls,   9: \" T|E..H|B\"\n",
      "trek(9):wars(6)           9 calls,  13: \"IS|Y|RA|CT| F\"\n",
      "noun(100):adj(98)      1000 calls, 167: \"f.t|^hea|aw$|^g|jo|rty|rt$|ot$|^wa|o.y|el ...\"\n",
      "adj(98):noun(100)       721 calls, 146: \"r.t|re$|f$|st$|at$|rse|b.t|a.l|ui|far|u.h ...\"\n",
      "noun(100):verb(94)     1000 calls, 168: \"am|er$|t.t|ir|po|ot|.as|^ar|^en|gu|.ne|ac ...\"\n",
      "verb(94):noun(100)     1000 calls, 170: \"c.n|p.y|sw|r.ad|^tr|ru|^fi|un.$|it$|b.y|^ ...\"\n",
      "rand(58):built(147)    1000 calls,  73: \"ia|_p|a.p|ee|_e|and|ets|^u|lti|^_.e|_s|_. ...\"\n",
      "built(147):rand(58)    1000 calls, 130: \"^i|se.$|^range$|Y|..E|xe|Wa|bo|ev|w$|xt|^ ...\"\n",
      "dog(100):cat(91)       1000 calls,  69: \"^HAVANESE$|E.S$|O.S$|N.S$|.AS|GS|.HI|RD|B ...\"\n",
      "cat(91):dog(100)        539 calls, 104: \"J.V|NX|H$|AN$|EX|OE|BAL|^TH|Y$|T$|R$|MES| ...\"\n",
      "movie(100):tv(97)      1000 calls, 154: \"^GR|R W|LAD|^CI|GO| . |AP.|^N|^RA|HIN|NC. ...\"\n",
      "tv(97):movie(100)      1000 calls, 146: \"MAS|^.OS|WIR|EER|OAP|4|H.W|6|.CI|X.$|.MO| ...\"\n",
      "sci(50):star(50)       1000 calls,  67: \"AL..|T..N|R.S| TO|.KA|KN|OS|MU|VE|NN|Ü|LE ...\"\n",
      "star(50):sci(50)       1000 calls,  76: \"UM|WES|CA|T. | ST|YN|LI..|F..D|GR|BU| GA| ...\"\n",
      "CPU times: user 8.05 s, sys: 23.4 ms, total: 8.07 s\n",
      "Wall time: 8.07 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1676"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time bbenchmark(calls=1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "This is encouraging! We took about 2 seconds longer, but improved on the total number of characters by about 4%. For 10 of the 22 cases we didn't reach the cutoff of 1000 calls, which means that we searched every feasible combination of the parts we have.  Let's try with 10,000 calls:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "win(34):lose(34)       1707 calls,  52: \"j|po|a.a|a..i|bu|ma|li|ls|a.t|vel|ho|xo|a ...\"\n",
      "lose(34):win(34)       3075 calls,  57: \"^s|ox|ss|^ki|i.$|go|^f|de|br|hu|ker|le$|e ...\"\n",
      "boy(10):girl(10)          9 calls,  11: \"de|a.$|c|as\"\n",
      "girl(10):boy(10)         13 calls,  10: \"a$|a.i|e.i\"\n",
      "drug(10):city(10)         3 calls,  15: \"ir|^e|o.$|f|x|q\"\n",
      "city(10):drug(10)        17 calls,  11: \"ri|an|h|a.e\"\n",
      "foo(21):bar(21)           1 calls,   3: \"f.o\"\n",
      "bar(21):foo(21)         205 calls,  24: \"k|ld|b|...n|ah|ar|or|z|A\"\n",
      "wars(6):trek(9)          21 calls,   9: \" T|E..H|B\"\n",
      "trek(9):wars(6)           9 calls,  13: \"IS|Y|RA|CT| F\"\n",
      "noun(100):adj(98)      2009 calls, 167: \"f.t|^hea|aw$|^g|jo|rty|rt$|ot$|^wa|o.y|el ...\"\n",
      "adj(98):noun(100)       721 calls, 146: \"r.t|re$|f$|st$|at$|rse|b.t|a.l|ui|far|u.h ...\"\n",
      "noun(100):verb(94)    10000 calls, 168: \"am|er$|t.t|ir|po|ot|.as|^ar|^en|gu|.ne|ac ...\"\n",
      "verb(94):noun(100)     3285 calls, 170: \"c.n|p.y|sw|r.ad|^tr|ru|^fi|un.$|it$|b.y|^ ...\"\n",
      "rand(58):built(147)    1427 calls,  73: \"ia|_p|a.p|ee|_e|and|ets|^u|lti|^_.e|_s|_. ...\"\n",
      "built(147):rand(58)   10000 calls, 130: \"^i|se.$|^range$|Y|ro|Wa|bo|ev|w$|xt|^d|^o ...\"\n",
      "dog(100):cat(91)      10000 calls,  69: \"^HAVANESE$|E.S$|O.S$|N.S$|.AS|GS|.HI|RD|B ...\"\n",
      "cat(91):dog(100)        539 calls, 104: \"J.V|NX|H$|AN$|EX|OE|BAL|^TH|Y$|T$|R$|MES| ...\"\n",
      "movie(100):tv(97)     10000 calls, 153: \"^GR|R W|LAD|^CI|GO| . |AP.|^N|^RA|HIN|NC. ...\"\n",
      "tv(97):movie(100)     10000 calls, 146: \"MAS|^.OS|WIR|EER|OAP|4|H.W|6|.CI|X.$|.MO| ...\"\n",
      "sci(50):star(50)      10000 calls,  67: \"AL..|T..N|R.S| TO|.KA|KN|OS|MU|NN|W.I|IG. ...\"\n",
      "star(50):sci(50)      10000 calls,  76: \"UM|WES|CA|T. | ST|YN|F..D|GR| GA|H.P|LO.| ...\"\n",
      "CPU times: user 20.2 s, sys: 40.4 ms, total: 20.3 s\n",
      "Wall time: 20.3 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1674"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time bbenchmark(calls=10000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We doubled the time and gained a few characters. How about 100,000 calls?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "win(34):lose(34)       1707 calls,  52: \"j|po|a.a|a..i|bu|ma|li|ls|a.t|vel|ho|xo|a ...\"\n",
      "lose(34):win(34)       3075 calls,  57: \"^s|ox|ss|^ki|i.$|go|^f|de|br|hu|ker|le$|e ...\"\n",
      "boy(10):girl(10)          9 calls,  11: \"de|a.$|c|as\"\n",
      "girl(10):boy(10)         13 calls,  10: \"a$|a.i|e.i\"\n",
      "drug(10):city(10)         3 calls,  15: \"ir|^e|o.$|f|x|q\"\n",
      "city(10):drug(10)        17 calls,  11: \"ri|an|h|a.e\"\n",
      "foo(21):bar(21)           1 calls,   3: \"f.o\"\n",
      "bar(21):foo(21)         205 calls,  24: \"k|ld|b|...n|ah|ar|or|z|A\"\n",
      "wars(6):trek(9)          21 calls,   9: \" T|E..H|B\"\n",
      "trek(9):wars(6)           9 calls,  13: \"IS|Y|RA|CT| F\"\n",
      "noun(100):adj(98)      2009 calls, 167: \"f.t|^hea|aw$|^g|jo|rty|rt$|ot$|^wa|o.y|el ...\"\n",
      "adj(98):noun(100)       721 calls, 146: \"r.t|re$|f$|st$|at$|rse|b.t|a.l|ui|far|u.h ...\"\n",
      "noun(100):verb(94)   100000 calls, 167: \"am|er$|t.t|ir|po|ot|.as|^ar|^en|gu|.ne|ac ...\"\n",
      "verb(94):noun(100)     3285 calls, 170: \"c.n|p.y|sw|r.ad|^tr|ru|^fi|un.$|it$|b.y|^ ...\"\n",
      "rand(58):built(147)    1427 calls,  73: \"ia|_p|a.p|ee|_e|and|ets|^u|lti|^_.e|_s|_. ...\"\n",
      "built(147):rand(58)   94795 calls, 127: \"^i|se.$|^range$|Y|ro|Wa|bo|ev|w$|xt|^d|^o ...\"\n",
      "dog(100):cat(91)     100000 calls,  69: \"^HAVANESE$|E.S$|O.S$|N.S$|.AS|GS|.HI|RD|B ...\"\n",
      "cat(91):dog(100)        539 calls, 104: \"J.V|NX|H$|AN$|EX|OE|BAL|^TH|Y$|T$|R$|MES| ...\"\n",
      "movie(100):tv(97)    100000 calls, 153: \"^GR|R W|LAD|^CI|GO| . |AP.|^N|^RA|HIN|NC. ...\"\n",
      "tv(97):movie(100)    100000 calls, 146: \"MAS|^.OS|WIR|EER|OAP|4|H.W|6|.CI|X.$|.MO| ...\"\n",
      "sci(50):star(50)     100000 calls,  67: \"AL..|T..N|I$|.KA|KN|OS|VE|I.O| TO| .RE|LE ...\"\n",
      "star(50):sci(50)     100000 calls,  75: \"UM|WES|CA|GR|LO.|F..D|^B|DEA| GA|H.P|I.L| ...\"\n",
      "CPU times: user 3min 8s, sys: 333 ms, total: 3min 8s\n",
      "Wall time: 3min 8s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1669"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time bbenchmark(calls=100000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We're slowly decreasing the total number of characters, but at the expense of increasing run time. I think if we want to make more progress, it is time to stop worrying about the search algorithm, and start worrying about what we're searching over.\n",
    "\n",
    "# New Parts: Repetition Characters\n",
    "\n",
    "Following a suggestion by Stefan Pochmann, I will generate two new classes of parts that use the repetition characters `'*'`, `'+'`, and `'?'`:\n",
    "\n",
    "- **pairs**: parts of the form `'A.*B'` where `'A'` and `'B'` are any two non-special characters that appear anywhere in any winner, the dot is always the second character, and the third character is one of the repetition characters. \n",
    "\n",
    "- **reps**: given a part such as `'a.c'`, insert any repetition character after any character in the part (yielding, for example, `'a*.c'`).\n",
    "Don't insert after `'^'` or `'$'`, and don't allow redundant parts like `'..*c'`.\n",
    "\n",
    "\n",
    "Here is a new version of `regex_covers` that adds the new parts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def regex_covers(winners, losers):\n",
    "    \"\"\"Generate regex components and return a dict of {regex: {winner...}}.\n",
    "    Each regex matches at least one winner and no loser.\"\"\"\n",
    "    losers_str = '\\n'.join(losers)\n",
    "    wholes = {'^'+winner+'$' for winner in winners}\n",
    "    parts  = {d for w in wholes for p in subparts(w) for d in dotify(p)}\n",
    "    reps   = {r for p in parts for r in repetitions(p)}\n",
    "    pool   = wholes | parts | pairs(winners) | reps                         \n",
    "    searchers = {p:re.compile(p, re.MULTILINE).search for p in pool}\n",
    "    return {p: Set(filter(searchers[p], winners)) \n",
    "            for p in pool\n",
    "            if not searchers[p](losers_str)}\n",
    "\n",
    "def pairs(winners, special_chars=Set('*+?^$.[](){}|\\\\')):\n",
    "    chars = Set(cat(winners)) - special_chars\n",
    "    return {A+'.'+q+B \n",
    "            for A in chars for B in chars for q in '*+?'}\n",
    "\n",
    "def repetitions(part):\n",
    "    \"\"\"Return a set of strings derived by inserting a single repetition character\n",
    "    ('+' or '*' or '?'), after each non-special character.  \n",
    "    Avoid redundant repetition of dots.\"\"\"\n",
    "    splits = [(part[:i], part[i:]) for i in range(1, len(part)+1)]\n",
    "    return {A + q + B \n",
    "            for (A, B) in splits\n",
    "            # Don't allow '^*' nor '$*' nor '..*' nor '.*.'\n",
    "            if not (A[-1] in '^$')\n",
    "            if not A.endswith('..')\n",
    "            if not (A.endswith('.') and B.startswith('.'))\n",
    "            for q in '*+?'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'test_new_parts passes'"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def test_new_parts():\n",
    "    assert repetitions('a') == {'a+', 'a*', 'a?'}\n",
    "    assert repetitions('ab') == {'a+b', 'a*b', 'a?b', \n",
    "                                 'ab+', 'ab*', 'ab?'}\n",
    "    assert repetitions('a.c') == {'a+.c', 'a*.c', 'a?.c',\n",
    "                                  'a.c+', 'a.*c', 'a.?c',\n",
    "                                  'a.+c', 'a.c*', 'a.c?'}\n",
    "    assert repetitions('^a..d$') == {'^a+..d$', '^a*..d$', '^a?..d$', \n",
    "                                     '^a..d+$', '^a..d*$', '^a..d?$'}\n",
    "    assert pairs({'ab', 'c'}) == {\n",
    "        'a.*a', 'a.*b', 'a.*c',\n",
    "        'a.+a', 'a.+b', 'a.+c',\n",
    "        'a.?a', 'a.?b', 'a.?c',\n",
    "        'b.*a', 'b.*b', 'b.*c',\n",
    "        'b.+a', 'b.+b', 'b.+c',\n",
    "        'b.?a', 'b.?b', 'b.?c',\n",
    "        'c.*a', 'c.*b', 'c.*c',\n",
    "        'c.+a', 'c.+b', 'c.+c',\n",
    "        'c.?a', 'c.?b','c.?c'}\n",
    "    assert len(pairs({'1...2...3', '($2.34)', '42', '56', '7-11'})) == 8 * 8 * 3\n",
    "    covers = regex_covers({'one', 'on'}, {'won', 'wuan', 'juan'})\n",
    "    assert (eliminate_dominated(covers) == {'e': {'one'}, '^o': {'on', 'one'}})\n",
    "    return 'test_new_parts passes'\n",
    "\n",
    "test_new_parts()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Let's take our new parts out for a spin and see what they can do:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' T|P.*E'"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "findregex(starwars, startrek)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "**Awesome!**  \n",
    "\n",
    "Remember, Randall had a ten character regex in the strip (see below); we previously got it down to nine, but we now have it down to **seven** with `' T|P.*E'`!\n",
    "\n",
    "<img src=\"http://norvig.com/regex_golf1.PNG\">\n",
    "\n",
    "**Update(Nov 2015)**: There are two new movies in the works; let's see what they do to our golf score:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' T|P.*E|KE'"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "starwars = starwars | {'THE FORCE AWAKENS'}\n",
    "startrek = startrek | {'BEYOND'}\n",
    "\n",
    "findregex(starwars, startrek)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Too bad; back to ten characters.\n",
    "\n",
    "How much more work are we doing with these additional parts?  Before, `regex_covers(winners, losers)` gave 1615 regexes, which were reduced to 49 by `simplify_covers`.  Now:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "13200"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "covers = regex_covers(winners, losers)\n",
    "len(covers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "90"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "covers2, partial = simplify_covers(covers)\n",
    "len(covers2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "So the total number of regexes is increased almost 10-fold, but after simplification the number is only  double what it was before.  (To put it another way, `simplify_covers` eliminated 99.3% of the parts.) That's not too bad; let's add *more* components.\n",
    "\n",
    "# New Parts: Longer Ones\n",
    "\n",
    "Previously we generated parts of length up to 4 characters.  Why not say \"[we're doing 5](http://www.theonion.com/articles/fuck-everything-were-doing-five-blades,11056/)\"?  The implementation is easy:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "SUBPARTS = 5 # Maximum length of a subpart\n",
    "\n",
    "def subparts(word):\n",
    "    \"Return a set of subparts of word, consecutive characters up to length 5.\"\n",
    "    return set(word[i:i+1+s] for i in range(len(word)) for s in range(SUBPARTS)) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "But how many more regex components does this give us?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "39537"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "covers = regex_covers(winners, losers)\n",
    "len(covers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "112"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "covers2, partial = simplify_covers(covers)\n",
    "len(covers2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "In the end the longer parts add only 22 new components, rejecting nearly 40,000 other parts. It is time to benchmark again. Remember our previous best was Branch and Bound with 100,000 calls, which yielded 1669 total characters in 170 seconds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "win(34):lose(34)       1000 calls,  47: \"i.+o|o.*o|a.a|po|a.t|j|bu|ce|ay.|ma|r.i|n ...\"\n",
      "lose(34):win(34)       1000 calls,  56: \"r.*y|i.e*$|^s|go|d..e|^f|n.*k|k.+g|hu|rk| ...\"\n",
      "boy(10):girl(10)         29 calls,  11: \"a.$|de|c|as\"\n",
      "girl(10):boy(10)         23 calls,   9: \"a$|^m*..i\"\n",
      "drug(10):city(10)        85 calls,  15: \"o.$|x|ir|f|q|^e\"\n",
      "city(10):drug(10)        45 calls,  11: \"ri|a.+e|h|k\"\n",
      "foo(21):bar(21)           1 calls,   3: \"foo\"\n",
      "bar(21):foo(21)        1000 calls,  23: \"^...a|k|...n|ld|b|ar|or\"\n",
      "wars(6):trek(9)          23 calls,   7: \" T|P.*E\"\n",
      "trek(9):wars(6)         169 calls,  12: \"I.?S|RA| F|Y\"\n",
      "noun(100):adj(98)      1000 calls, 161: \"^wa|l.v|m.+n|me?$|.i.*d|....o|an*.e$|..k$ ...\"\n",
      "adj(98):noun(100)      1000 calls, 140: \"e.+y|^..l*$|l.*s|rs?e$|a.l|ei?t|st$|en$|f ...\"\n",
      "noun(100):verb(94)     1000 calls, 168: \"h.+g|mp*.n|p.*r|..h.|mb*e|ea?s|^k?i|.ne|. ...\"\n",
      "verb(94):noun(100)     1000 calls, 162: \"rr|tar|o.b|^..p?l|^f?..$|buy|f$|^fi|as*k| ...\"\n",
      "rand(58):built(147)    1000 calls,  72: \"ee|^_.*n|a.p|ia|an*d.|^_.?e|tst|e._+$|o.c ...\"\n",
      "built(147):rand(58)    1000 calls, 130: \"^rang|r...$|c.*t|ra*.i|^l*i|al*s|ug|^m?a| ...\"\n",
      "dog(100):cat(91)       1000 calls,  43: \"E.+S$|I.*S$|H.*N.S|.HI|G.?S|TES|.SO|W |O.D.\"\n",
      "cat(91):dog(100)       1000 calls, 105: \"J.V|RA*$|R.*A.$|LD?$|N.*X|M$|M...$|E.*O.$ ...\"\n",
      "movie(100):tv(97)      1000 calls, 148: \" TH.+N| A*. |R...R|GR?O|IS?.$|A.C*E$|^GR| ...\"\n",
      "tv(97):movie(100)      1000 calls, 148: \"4|HT?.W|..CH*I|XI$|PO*R|R..AN|MAS|..AY.|O ...\"\n",
      "sci(50):star(50)       1000 calls,  71: \"AN?L..|T.V?.N|RL?.S|N.*RE|.S.+H|LER|.KA|G ...\"\n",
      "star(50):sci(50)       1000 calls,  74: \"U.*R.|GR|LO.|F.+D|I.Y*N| T*R|G.*Y|LES?$|E ...\"\n",
      "CPU times: user 4min 23s, sys: 2 s, total: 4min 25s\n",
      "Wall time: 4min 25s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1616"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time bbenchmark(calls=1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We reduced the total characters by about 4%, although it did take longer, even with only 1,000 calls. And notice we no longer need `'^HAVANESE$'`; instead we have `'H.*N.S'`, which saves 4 characters, and, look how many breeds it matches:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'AFGHAN HOUNDS',\n",
       " 'BASSET HOUNDS',\n",
       " 'BLOODHOUNDS',\n",
       " 'CHINESE CRESTED',\n",
       " 'CHINESE SHAR-PEI',\n",
       " 'DACHSHUNDS',\n",
       " 'HAVANESE',\n",
       " 'IRISH WOLFHOUNDS',\n",
       " 'ITALIAN GREYHOUNDS',\n",
       " 'TREEING WALKER COONHOUNDS'}"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matches('H.*N.S', dogs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Let's continue benchmarking:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "win(34):lose(34)      10000 calls,  46: \"i.+o|j|bu|oo|a.t|n.o*e|ma|po|ie.|ay.|e.?a ...\"\n",
      "lose(34):win(34)      10000 calls,  55: \"r.*y|i.e*$|^s|go|de|do|^f|la.$|al|n.*k|k. ...\"\n",
      "boy(10):girl(10)         29 calls,  11: \"a.$|de|c|as\"\n",
      "girl(10):boy(10)         23 calls,   9: \"a$|^m*..i\"\n",
      "drug(10):city(10)        85 calls,  15: \"o.$|x|ir|f|q|^e\"\n",
      "city(10):drug(10)        45 calls,  11: \"ri|a.+e|h|k\"\n",
      "foo(21):bar(21)           1 calls,   3: \"foo\"\n",
      "bar(21):foo(21)        6151 calls,  23: \"^...a|k|...n|ld|b|ar|or\"\n",
      "wars(6):trek(9)          23 calls,   7: \" T|P.*E\"\n",
      "trek(9):wars(6)         169 calls,  12: \"I.?S|RA| F|Y\"\n",
      "noun(100):adj(98)     10000 calls, 160: \"^wa|l.v|m.+n|me?$|.i.*d|....o|an*.e$|..k$ ...\"\n",
      "adj(98):noun(100)     10000 calls, 136: \"e.+y|^..l*$|l.*s|rs?e$|a.l|ei?t|st$|en$|f ...\"\n",
      "noun(100):verb(94)    10000 calls, 167: \"h.+g|mp*.n|p.*r|..h.|mb*e|ea?s|^k?i|.ne|. ...\"\n",
      "verb(94):noun(100)    10000 calls, 162: \"rr|tar|o.b|^..p?l|^f?..$|buy|f$|^fi|as*k| ...\"\n",
      "rand(58):built(147)   10000 calls,  69: \"ee|^_.*n|a.p|ia|an*d.|^_.?e|tst|_s|.G|_.o ...\"\n",
      "built(147):rand(58)   10000 calls, 124: \"^rang|r...$|c.*t|ra*.i|^l*i|al*s|ug|^m?a| ...\"\n",
      "dog(100):cat(91)      10000 calls,  43: \"E.+S$|I.*S$|H.*N.S|.HI|G.?S|TES|.SO|W |O.D.\"\n",
      "cat(91):dog(100)      10000 calls, 104: \"J.V|RA*$|R.*A.$|LD?$|N.*X|M$|M...$|E.*O.$ ...\"\n",
      "movie(100):tv(97)     10000 calls, 148: \" TH.+N| A*. |R...R|GR?O|IS?.$|A.C*E$|^GR| ...\"\n",
      "tv(97):movie(100)     10000 calls, 148: \"4|HT?.W|..CH*I|XI$|PO*R|R..AN|MAS|..AY.|O ...\"\n",
      "sci(50):star(50)      10000 calls,  70: \"AN?L..|T.V?.N|RL?.S|N.*RE|.S.+H|LER|.KA|P ...\"\n",
      "star(50):sci(50)      10000 calls,  73: \"U.*R.|GR|LO.|F.+D|I.Y*N| T*R|G.*Y|AE?.W|E ...\"\n",
      "CPU times: user 4min 38s, sys: 2 s, total: 4min 40s\n",
      "Wall time: 4min 40s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1596"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time bbenchmark(calls=10000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We're making good progress. What next? We now have so many parts, that many of the searches do not complete. Suppose one of our first choices was wrong, and the search took a part that does not belong in an optimal solution.  We might well spend all our calls on the half of the search tree that keeps the part, never exploring a part of the tree without it.  I'd like to alter the search algorithm to get us out of that rut.\n",
    "\n",
    "# Searching: Random Restart\n",
    "\n",
    "\n",
    "One way out of the rut is to run the search for a while, then stop it, and run a different search, that explores a different part of the search space. This is called a *random restart search*. How do we get a *different* search when we restart? I can think of two easy things to vary:\n",
    "    \n",
    "+ The '4' in the `score` function. That is, vary the tradeoff between number of winners matched and number of characters in a regex.\n",
    "+ The tie-breaker. In case of a tie on `max(covers, key=score)`, Python always picks the first component. Let's make it choose a different one each time.\n",
    "\n",
    "The first of these is easy; we can use the `random.choice` function to choose an integer, K, to serve as the tradeoff factor. The second is easy too. We could write an alternative to the `max` function, say `max_random_tiebreaker`. That would work, but an easier approach is to build the tiebreaker into the `score` function. In addition to awarding points for matching winners, and subtracting a point for each character in the solution, we will have `score` add in a random number. We'll call this the \"fuzz factor\" and use the variable `F` to determine how big it is.  If the fuzz factor is a random number between 0 and 1, then all it does is serve as a tiebreaker.  But if it is a random number that can be larger than 1, then sometimes it will cause `max` to pick a best part that does not have quite the best score.  We're not sure how much randomness is best, so we'll let the values of `K` and `F` vary from one choice to the next."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def bb_findregex(winners, losers, calls=10000, restarts=10):\n",
    "    \"Find the shortest disjunction of regex components that covers winners but not losers.\"\n",
    "    bb = BranchBoundRandomRestart(winners, calls)\n",
    "    covers = eliminate_dominated(regex_covers(winners, losers))\n",
    "    for _ in range(restarts):\n",
    "        bb.calls = calls\n",
    "        bb.search(covers.copy())\n",
    "        if bb.calls > 0: # If search was not cut off, we have optimal solution\n",
    "            return bb \n",
    "    return bb\n",
    "\n",
    "class BranchBoundRandomRestart(BranchBound):\n",
    "    def search(self, covers, partial=None):\n",
    "        \"\"\"Recursively extend partial regex until it matches all winners in covers.\n",
    "        Try all reasonable combinations until we run out of calls.\"\"\"\n",
    "        if self.calls <= 0: \n",
    "            return partial, covers\n",
    "        self.calls -= 1\n",
    "        covers, partial = simplify_covers(covers, partial)\n",
    "        if not covers: # Nothing left to cover; solution is complete\n",
    "            self.cheapest = min(partial, self.cheapest, key=len)\n",
    "        elif len(OR(partial, min(covers, key=len))) < len(self.cheapest):\n",
    "            # Try with and without the greedy-best component\n",
    "            K = random.choice((2, 3, 4, 4, 4, 5, 6))\n",
    "            F = random.choice((0.1, 0.1, 2.0))\n",
    "            def score(c): return K * len(covers[c]) - len(c) + random.uniform(0., F)\n",
    "            best = max(covers, key=score) # Best component\n",
    "            covered = covers[best] # Set of winners covered by r\n",
    "            covers.pop(best)\n",
    "            self.search({c:covers[c]-covered for c in covers}, OR(partial, best))\n",
    "            self.search(covers, partial)\n",
    "        return self.cheapest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "win(34):lose(34)        100 calls,  49: \"i.+o|o.*o|.f|ce|a.a|po|bu|ay.|ma|n.e|j|an ...\"\n",
      "lose(34):win(34)        100 calls,  52: \"r.*y|^d|^s|go|m.+a|^f|....k|^.?la|ki*..$| ...\"\n",
      "boy(10):girl(10)         29 calls,  11: \"a.$|c|de|as\"\n",
      "girl(10):boy(10)         21 calls,   9: \"a$|^m*..i\"\n",
      "drug(10):city(10)        91 calls,  15: \"o.$|x|ir|f|q|^e\"\n",
      "city(10):drug(10)        49 calls,  11: \"ri|h|a.+e|k\"\n",
      "foo(21):bar(21)           1 calls,   3: \"foo\"\n",
      "bar(21):foo(21)         100 calls,  23: \"..r..|^...a|k|A|ld|...n\"\n",
      "wars(6):trek(9)          23 calls,   7: \" T|P.*E\"\n",
      "trek(9):wars(6)         100 calls,  12: \"I.?S|TI|H |Y\"\n",
      "noun(100):adj(98)       100 calls, 160: \"^wa|l.v|m.+n|me?$|....o|.i.*d|ar*c.$|wo|. ...\"\n",
      "adj(98):noun(100)       100 calls, 128: \"e.+y|^o*..$|l.*s|ll|rs?e$|ei?t|en$|st$|fa ...\"\n",
      "noun(100):verb(94)      100 calls, 163: \"h.+g|mo?.n|p.*r|..h.|mb*e|t.*o|.ne|^k?i|f ...\"\n",
      "verb(94):noun(100)      100 calls, 161: \"rr|tar|o.b|^..p?l|^s*..$|f$|buy|as*k|r.ad ...\"\n",
      "rand(58):built(147)     100 calls,  69: \"ee|^_.*n|a.p|ia|an*d.|^_.?e|tst|_s|_a?.o| ...\"\n",
      "built(147):rand(58)     100 calls, 119: \"^rang|r...$|c.*t|Wa|^d?i|al*s|ug|^m?a|o.* ...\"\n",
      "dog(100):cat(91)        100 calls,  43: \"E.+S$|I.*S$|H.*N.S|.HI|G.?S|.SO|W |TES|O.D.\"\n",
      "cat(91):dog(100)        100 calls,  97: \"J.V|RA*$|T$|LI*$|AN?$|N.*X|M$|F$|S.+E$|E. ...\"\n",
      "movie(100):tv(97)       100 calls, 144: \" TH.+N|R...R| A*. |GO|UC*. |^N|A.C*E$|^GR ...\"\n",
      "tv(97):movie(100)       100 calls, 148: \"4|HT?.W|..CH*I|XI$|PO*R|R..AN|MAS| .E.?E| ...\"\n",
      "sci(50):star(50)        100 calls,  67: \"AN?L..|T.V?.N|.S.+H|.KA|IL?.O|N.*RE|OS|LE ...\"\n",
      "star(50):sci(50)        100 calls,  73: \"U.*R.|GR|LO.|F.+D|I.Y*N| T*R|G.*Y| M*.T|E ...\"\n",
      "CPU times: user 4min 39s, sys: 2.33 s, total: 4min 41s\n",
      "Wall time: 4min 41s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1564"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time bbenchmark(calls=100)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Remember, when it says \"100 calls\" here, it really means 1,000 calls, because we are doing 10 random restarts. This looks very promising; even with only 100 calls per restart, we're doing better than 100,000 calls without restarts.  Let's continue:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "win(34):lose(34)       1000 calls,  46: \"i.+o|o.*o|bu|a.t|j|ma|po|ie.|n.e|ay.|ar*d ...\"\n",
      "lose(34):win(34)       1000 calls,  55: \"r.*y|i.e*$|^s|go|de|^f|do|la.$|al|k.+g|hu ...\"\n",
      "boy(10):girl(10)         31 calls,  11: \"a.$|de|c|as\"\n",
      "girl(10):boy(10)         21 calls,   9: \"a$|^m*..i\"\n",
      "drug(10):city(10)        89 calls,  15: \"o.$|x|ir|f|q|^e\"\n",
      "city(10):drug(10)        41 calls,  11: \"ri|a.+e|h|k\"\n",
      "foo(21):bar(21)           1 calls,   3: \"foo\"\n",
      "bar(21):foo(21)        1000 calls,  23: \"^...a|k|...n|ld|b|or|ar\"\n",
      "wars(6):trek(9)          33 calls,   7: \" T|P.*E\"\n",
      "trek(9):wars(6)         153 calls,  12: \"I.?S|RA| F|Y\"\n",
      "noun(100):adj(98)      1000 calls, 159: \"^wa|l.v|m.+n|me?$|....o|.i.*d|an*.e$|..k$ ...\"\n",
      "adj(98):noun(100)      1000 calls, 128: \"e.+y|^o*..$|l.*s|ll|rs?e$|ei?t|st$|en$|fa ...\"\n",
      "noun(100):verb(94)     1000 calls, 162: \"h.+g|mp*.n|p.*r|..h.|mb*e|^k?i|.ne|or.?$| ...\"\n",
      "verb(94):noun(100)     1000 calls, 159: \"rr|tar|o.b|^..p?l|^s*..$|f$|buy|as*k|r.ad ...\"\n",
      "rand(58):built(147)    1000 calls,  69: \"ee|ia|^_.*n|a.p|an*d.|^_.?e|tst|_a?.o|ga| ...\"\n",
      "built(147):rand(58)    1000 calls, 119: \"^rang|r...$|c.*t|Wa|^d?i|al*s|ug|o.*p..|Y ...\"\n",
      "dog(100):cat(91)       1000 calls,  43: \"E.+S$|I.*S$|H.*N.S|.HI|G.?S|TES|.SO|W |O.D.\"\n",
      "cat(91):dog(100)       1000 calls,  96: \"J.V|RA*$|T$|LD?$|AN?$|N.*X|M$|Y$|S.+E$|M. ...\"\n",
      "movie(100):tv(97)      1000 calls, 139: \" TH.+N| A*. |R...R|GO|UC*. |^N|NC.$|A.NI| ...\"\n",
      "tv(97):movie(100)      1000 calls, 148: \"4|HT?.W|..CH*I|XI$|PO*R|..AY.|O.+L.$|R..A ...\"\n",
      "sci(50):star(50)       1000 calls,  67: \"AN?L..|T.V?.N|.S.+H|.KA|IL?.O|N.*RE|OS|NN ...\"\n",
      "star(50):sci(50)       1000 calls,  73: \"U.*R.|GR|LO.|F.+D|I.+H$| T*R|G.*NE| M*.T| ...\"\n",
      "CPU times: user 4min 56s, sys: 3.13 s, total: 4min 59s\n",
      "Wall time: 4min 59s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1554"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time bbenchmark(calls=1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "win(34):lose(34)      10000 calls,  46: \"i.+o|o.*o|bu|a.t|j|ma|po|n.e|ay.|ar*d|e.? ...\"\n",
      "lose(34):win(34)      10000 calls,  52: \"^d|r.*y|^s|go|m.+a|^f|^.?la|....k|ki*..$| ...\"\n",
      "boy(10):girl(10)         29 calls,  11: \"a.$|de|c|as\"\n",
      "girl(10):boy(10)         21 calls,   9: \"a$|^m*..i\"\n",
      "drug(10):city(10)       105 calls,  15: \"x|o.$|ir|f|q|^e\"\n",
      "city(10):drug(10)        39 calls,  11: \"ri|a.+e|h|k\"\n",
      "foo(21):bar(21)           1 calls,   3: \"foo\"\n",
      "bar(21):foo(21)        6049 calls,  23: \"^...a|k|...n|ld|b|ar|or\"\n",
      "wars(6):trek(9)          23 calls,   7: \" T|P.*E\"\n",
      "trek(9):wars(6)         147 calls,  12: \"I.?S|TI|H |Y\"\n",
      "noun(100):adj(98)     10000 calls, 158: \"^wa|l.v|m.+n|me?$|....o|.i.*d|a.e$|..k$|^ ...\"\n",
      "adj(98):noun(100)     10000 calls, 128: \"e.+y|^o*..$|ll|l.*s|rs?e$|ei?t|en$|i..l|l ...\"\n",
      "noun(100):verb(94)    10000 calls, 163: \"h.+g|mp*.n|p.*r|..h.|mb*e|^k?i|.ne|.t.*y| ...\"\n",
      "verb(94):noun(100)    10000 calls, 157: \"rr|tar|o.b|^..p?l|^s*..$|f$|buy|as*k|r.ad ...\"\n",
      "rand(58):built(147)   10000 calls,  67: \"ee|ia|^_.*n|a.p|and|^_.?e|tst|_a?.o|ga|.G ...\"\n",
      "built(147):rand(58)   10000 calls, 121: \"^rang|r...$|c.*t|Wa|al*s|ug|^l*i|o.*p..|Y ...\"\n",
      "dog(100):cat(91)      10000 calls,  43: \"E.+S$|I.*S$|H.*N.S|.HI|G.?S|TES|.SO|W |O.D.\"\n",
      "cat(91):dog(100)      10000 calls,  96: \"J.V|RA*$|T$|LD?$|AN?$|N.*X|M$|M...$|Y$|M. ...\"\n",
      "movie(100):tv(97)     10000 calls, 141: \" TH.+N| A*. |R...R|GR?O|UC*. |A.C*E$|^GR| ...\"\n",
      "tv(97):movie(100)     10000 calls, 148: \"4|HT?.W|..CH*I|XI$|PO*R|..AY.|R..AN|MAS|O ...\"\n",
      "sci(50):star(50)      10000 calls,  67: \"AN?L..|T.V?.N|.S.+H|.KA|OS|NN|I.O|OD|^P|N ...\"\n",
      "star(50):sci(50)      10000 calls,  72: \"U.*R.|GR|LO.|I.+H$|F.+D| T*R|G.*Y|YN|^B|I ...\"\n",
      "CPU times: user 8min 3s, sys: 11.9 s, total: 8min 15s\n",
      "Wall time: 8min 15s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1550"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time bbenchmark(calls=10000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Just One More Thing: Negative Lookahead\n",
    "----\n",
    "\n",
    "In the `foo` versus `bar` example, we have a big asymmetry in the solution lengths: three letter for `'foo'` compared to 23 characters in the other direction.  But if you are a real [regular expression superhero](https://xkcd.com/208/), then you might know about [*negative lookahead assertions*](http://docs.python.org/2/howto/regex.html#lookahead-assertions) and you could solve `bar` versus `foo` like this:                                                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "not_foo = '^(?!.*foo)'\n",
    "not mistakes(not_foo, bar, foo)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Whoa&mdash;what just happened there? The form `'^(?!.*foo)'` means \"starting from the beginning of the line, look ahead for `'.*foo'` (that is, any number of characters followed by `'foo'`). If it is there, then fail, else succeeed.\" That's just what we need to match all the non-foo strings in the `bar` collection. Let's apply this idea to the complete benchmark and see how many characters we save.  We'll use the `SOLUTION` dict that was compiled by the previous call to  `benchmark`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "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 15.8 ms, sys: 291 µs, total: 16.1 ms\n",
      "Wall time: 16 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1429"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def consider_negative_lookahead(W, L): \n",
    "    \"Return either SOLUTION[W, L] or negative lookup of SOLUTION[L, W], whichever is shorter.\"\n",
    "    solution = min(SOLUTION[W, L], '^(?!.*(' + SOLUTION[L, W] + '))',\n",
    "                   key=len)\n",
    "    assert not mistakes(solution, W, L)\n",
    "    return solution\n",
    "    \n",
    "%time sum(len(consider_negative_lookahead(W, L)) for (W, _, _, L) in EXAMPLES)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Very nice! Almost a 10% improvement, and it took almost no additional time at all.  \n",
    "\n",
    "# Summary of Results\n",
    "\n",
    "Here is a plot of results. Note that every time you re-run this notebook, the timing and the exact number of characters will vary a little; these numbers reflect rrsults from a previous run.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAgAAAAEPCAYAAAA0xnyyAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xl8FdX5+PHPk0AgZCNskT1h3zEQUUQgKiICyqbVYI0x\naBV/ghW3KiCh1NYiYgvWXQSUTYuyg3xFwmJtAZFFxbJIUCAFkRCSAEkIz++Pe3NJyE1ySXITIM/7\n9ZoXd845c+bMhcs8M3POGVFVjDHGGFO5+FR0A4wxxhhT/iwAMMYYYyohCwCMMcaYSsgCAGOMMaYS\nsgDAGGOMqYQsADDGGGMqIa8FACIyQ0SOiMjOPGnzReQb57JfRL5xpoeLyOk8ea/n2aariOwUkT0i\n8ndvtdcYY4ypTKp4se73genA7NwEVb0n97OITAFO5Cm/V1Uj3dTzBjBCVTeJyAoR6aeqq7zVaGOM\nMaYy8NodAFXdAKS4yxMRAX4DzCuqDhGpDwSp6iZn0mxgcFm20xhjjKmMKqoPQE/giKruy5MW4bz9\nnygiNzjTGgIH85Q55EwzxhhjTCl48xFAUWKAuXnWDwONVTVFRLoAi0SkfcU0zRhjjLnylXsAICJV\ngCFAl9w0Vc0Cspyft4rIPqAljiv+Rnk2b+RMc1evvdTAGGNMpaKqUtJtK+IRQB9gl6oezk0QkToi\n4uv83AzHyf9HVU0GTorItc5+A/cBiwqrWFVt8eIyYcKECm/Dlb7Yd2zf85Wy2Hfs/aW0vDkMcB7w\nL6CViPwsIg84s+6mYOe/XsB257DAj4GHVTV3h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SEZcuWkZaWRnJyMmFhYYwaNSpf/rPPPktaWhonT55k\n5MiRDB06tNAx2iJCTEwMaWlp/Prrr/Tp04c777zT82MqQknHhasq586dc/s2vwu9+eab3Hfffa51\nPz8/7rnnniIDhxUrVnDbbbcB0LBhQ8aPH098fHyBcseOHWPYsGG8+OKLpKSkEBUVVWAWwX379nHu\n3DlatGhBYGAgDz74IC+//LLb/cbExNC1a1eOHz/Oiy++yJ133um6av/uu+945JFHmDNnDkeOHKFG\njRo8+uijrm1FxPV9rF69miFDhjBz5kx+85vfuOqeNWsW2dnZxX5nxhhTUpUzALgEVatWjWHDhvH9\n998XWiYmJobjx49z5MgRt/m5L3gA8PX1Zfjw4fzyyy+uE1NqaiojRoygQYMGNGrUiPHjx3Pu3DkA\n9u7dS+/evalZsyZ169YlJiYGgF69egHQuXNngoKCXK8GHjhwIPXq1aNWrVrcfvvt+ebkj46OZty4\ncdxwww0EBAQQGxvLhg0beOyxxwgKCmL06NEF2p6VlcXatWvp3bu3K61Vq1Y88MADtGvXrtDvZMWK\nFfTv3x+AIUOGMGjQILevB/7kk0/o0KEDw4YNw8/Pj4SEBLZv357v9cPLly9nwIABAFxzzTXce++9\nbq/+d+/ezTfffMPEiROpVq0aQ4cOpVOnTixcuBCAOXPmcMcdd7iOf9KkSXzyySdkZGTk+7tatmwZ\nd999N/PmzeOOO+5w5TVq1IjQ0FC++uqrQo/bGGNKywKAvNatAxHPlnXrymSXuSfsU6dOsWDBArp3\n7+42Pycnh9mzZ9OsWTPCwsKKrTcrK4vZs2fTvHlz6tSpAzgeKfj5+bFv3z6++eYbVq9ezbvvvgvA\n+PHj6devHydOnODQoUOuOxG5jxx27NhBWload911F+fOnWPEiBH89NNP/PTTT/j7+/PYY4/l2/+H\nH37IO++8Q3p6OjNnzqRnz5784x//IC0tjWnTphVo7549e/Dx8aFBgwYef3fZ2dls2LCBW265xe13\nltd3333nerQAUKNGDVq0aMG3337rSluxYoUrACjKd999R7NmzQgICHClde7cme+++87tvpo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rSEiINm/eXN977z13/IgRIzQgIECDg4O1SpUqGhUVpVOnTi02v2nTpunQoUM9wnbu3KlB\nQUF6+vRpzcjI0DFjxmjdunW1WrVq2rp1a33//fdVVXXSpEkaGRmpwcHB2qhRI124cKE7j7feeksj\nIiI0NDRUV61apSdPntTo6GgNDg7WO++8U+Pi4tTPz09zc3NVVTU6OloXLVrkUY5PP/1UGzdurGFh\nYfrMM88UKXtycrJHHqqqK1euVD8/P50+fbo7bOPGjdquXTsNDQ3ViIgIHTBggGZmZqqq6meffaat\nWrXS4OBg7d+/v/bt21dfeuklVVXdunWriojHj5+fnyYlJWliYqJ27txZq1Wrpk2bNtU1a9a495ee\nnq5DhgzRmjVrar169fSll17SvLw8VVVdsmSJ3n///e60Cxcu1Pr162tqaqrX30///v3d9a2q+uKL\nLxYpU8Fj3bx5s951110aGBioXbp0KZLvpEmTNDw8XMPDw3Xy5MkecfnHlu+zzz7TsLAwjYuLU1XV\nn//857pu3Tqv5fwxnzPGmO855+oPvm7acsDmpnXPPfcwduxYhg8fXtZFAVyvGw4fPpxdu3aVaTkS\nEhIYM2YMf//7373G2zljTPlwvcsBWwPA3DS2b99O48aNqVGjBsuXL3ePYyjJa5Pme3bOGFM+XG8D\noEK+BWBuTocPH2bAgAFkZ2fTqFEj/vznP9vF3xhjimE9AMYYD3bOGFM+XG8PQIV9C8AYY4zxpZEj\nR1K7dm2aN29eJG727Nn4+flx9uxZwDU9eNu2bWnRogVt27Zl69at7rSXLl3iqaee4s4776RJkyas\nXr26VMprjwCMMcYYH3jiiScYP348w4YN8wg/fvw4mzZt8phUrGbNmqxfv57bbruNxMREHnroIfer\n2DNmzOC2225zT9V95syZUimvPQIwxniwc8aYHy4lJYVevXp5LFTWv39/YmNj6d27N59//jnh4eEe\n26gqNWrU4F//+hf+/v5ERUVx+PBhAgMDr7gvGwRYAjfDcrLGGGPKn7Vr11K3bl1atGhRbJoPPviA\nNm3a4O/v716fIyYmhvj4eBo1asT8+fOpVauWz8tWamMARO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GsAGGOMMRWQNQCMMcaYCsgaAMYYY0wFZA0AY4wxpgKyBoAxxhhTAf0/8A6Pvmc+\nD6cAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x106402390>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#        Algorithm                   Style  Times            Total character counts\n",
    "DATA = [('Greedy',                   'gD-', [6],             [1740]),\n",
    "        ('BB (1/10/100K)',           'bo-', [8, 21, 196],    [1676, 1674, 1669]),\n",
    "        ('BB + Parts (1/10K)',       'kd-', [272, 288],      [1595, 1587]),\n",
    "        ('BB Restart (1/10/100K)',   'rs-', [289, 303, 493], [1560, 1556, 1547]),\n",
    "        ('BB Restart NegLook (100K)','m*-', [493],           [1426])]\n",
    "\n",
    "def display(data=DATA):\n",
    "    fig = plt.figure()\n",
    "    ax = fig.add_subplot(111)\n",
    "    for (label, line, times, counts) in data:\n",
    "        plt.plot(times, counts, line, label=label)\n",
    "        x, y = times[-1], counts[-1]\n",
    "        offset = (-22, -15) if line in ('rs-', 'm*-') else (10, -5)\n",
    "        ax.annotate(str(y), xy=(x, y), xytext=offset, textcoords='offset points')\n",
    "    plt.xlabel('Time (seconds)'); plt.ylabel('Solution size (total chars)')\n",
    "    plt.legend(loc='lower left');\n",
    "\n",
    "display()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We've made great strides, decreasing the total solution length by 20%.  (It is up to you whether that 20% improvement is worth the increase in time from 6 seconds to 8 minutes.)\n",
    "\n",
    "# Profiling Again\n",
    "\n",
    "Now where does the time go? Let's check again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         59623899 function calls (59278679 primitive calls) in 36.067 seconds\n",
      "\n",
      "   Ordered by: cumulative time\n",
      "\n",
      "   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
      "        1    0.000    0.000   36.067   36.067 {built-in method builtins.exec}\n",
      "        1    0.000    0.000   36.067   36.067 <string>:1(<module>)\n",
      "        1    0.002    0.002   36.067   36.067 <ipython-input-40-69eab5774964>:21(findregex)\n",
      "        1    0.072    0.072   36.066   36.066 <ipython-input-56-6db5f5ee7e3e>:1(bb_findregex)\n",
      "100178/10    0.781    0.000   24.877    2.488 <ipython-input-56-6db5f5ee7e3e>:13(search)\n",
      "   100000    0.593    0.000   20.145    0.000 <ipython-input-31-c9c277f8c298>:1(simplify_covers)\n",
      "   209152    2.074    0.000   11.561    0.000 <ipython-input-33-2d740317bec1>:1(eliminate_dominated)\n",
      "        1    0.007    0.007   10.413   10.413 <ipython-input-44-3e740ef01568>:1(regex_covers)\n",
      "  4047977    2.941    0.000    8.916    0.000 {built-in method builtins.any}\n",
      "        1    0.104    0.104    8.110    8.110 <ipython-input-44-3e740ef01568>:9(<dictcomp>)\n",
      "   209151    0.747    0.000    8.080    0.000 <ipython-input-34-656b8fb485f1>:1(select_necessary)\n",
      "    89666    0.043    0.000    8.006    0.000 re.py:222(compile)\n",
      "    89666    0.533    0.000    7.963    0.000 re.py:278(_compile)\n",
      "    89666    0.449    0.000    7.330    0.000 sre_compile.py:531(compile)\n",
      " 18054570    4.510    0.000    4.745    0.000 <ipython-input-33-2d740317bec1>:10(<genexpr>)\n",
      "    89666    0.335    0.000    3.693    0.000 sre_parse.py:819(parse)\n",
      "   209151    0.801    0.000    3.453    0.000 __init__.py:505(__init__)\n",
      "   209151    1.187    0.000    3.322    0.000 <ipython-input-34-656b8fb485f1>:5(<setcomp>)\n",
      "    89666    0.161    0.000    2.947    0.000 sre_compile.py:516(_code)\n",
      "    89666    0.187    0.000    2.930    0.000 sre_parse.py:429(_parse_sub)\n",
      "    50084    0.587    0.000    2.783    0.000 {built-in method builtins.max}\n",
      "   209152    1.339    0.000    2.649    0.000 {built-in method builtins.sorted}\n",
      "   209151    0.408    0.000    2.626    0.000 __init__.py:574(update)\n",
      "    89666    1.184    0.000    2.626    0.000 sre_parse.py:491(_parse)\n",
      "   636500    0.910    0.000    2.196    0.000 <ipython-input-56-6db5f5ee7e3e>:26(score)\n",
      "        1    1.683    1.683    2.164    2.164 <ipython-input-44-3e740ef01568>:10(<dictcomp>)\n",
      "    89666    0.472    0.000    1.407    0.000 sre_compile.py:412(_compile_info)\n",
      "171350/89666    0.873    0.000    1.369    0.000 sre_compile.py:64(_compile)\n",
      "   426948    0.469    0.000    1.331    0.000 <ipython-input-32-308f8216e1f8>:1(OR)\n",
      "  2167485    0.983    0.000    1.311    0.000 <ipython-input-33-2d740317bec1>:6(signature)\n",
      "   209151    0.622    0.000    1.310    0.000 {built-in method _collections._count_elements}\n",
      "  4734318    1.287    0.000    1.287    0.000 <ipython-input-34-656b8fb485f1>:5(<genexpr>)\n",
      "   636500    1.118    0.000    1.180    0.000 random.py:342(uniform)\n",
      "  1147585    0.351    0.000    1.049    0.000 {built-in method builtins.isinstance}\n",
      "11387014/11305330    0.956    0.000    0.980    0.000 {built-in method builtins.len}\n",
      "   444972    0.606    0.000    0.818    0.000 {method 'join' of 'str' objects}\n",
      "   209151    0.416    0.000    0.698    0.000 abc.py:178(__instancecheck__)\n",
      "  2988397    0.688    0.000    0.688    0.000 <ipython-input-34-656b8fb485f1>:4(<genexpr>)\n",
      "253034/171350    0.566    0.000    0.684    0.000 sre_parse.py:167(getwidth)\n",
      "   480786    0.209    0.000    0.605    0.000 sre_parse.py:247(get)\n",
      "    89666    0.481    0.000    0.481    0.000 {method 'search' of '_sre.SRE_Pattern' objects}\n",
      "   490104    0.334    0.000    0.478    0.000 sre_parse.py:157(__getitem__)\n",
      "   570452    0.474    0.000    0.474    0.000 sre_parse.py:226(__next)\n",
      "   532234    0.368    0.000    0.368    0.000 {built-in method builtins.min}\n",
      "  2239948    0.317    0.000    0.317    0.000 {method 'append' of 'list' objects}\n",
      "   418302    0.282    0.000    0.282    0.000 _weakrefset.py:70(__contains__)\n",
      "   100168    0.097    0.000    0.270    0.000 random.py:250(choice)\n",
      "    76784    0.248    0.000    0.248    0.000 <ipython-input-34-656b8fb485f1>:8(<dictcomp>)\n",
      "    81684    0.148    0.000    0.241    0.000 sre_compile.py:386(_simple)\n",
      "   399102    0.153    0.000    0.234    0.000 sre_parse.py:165(append)\n",
      "    89666    0.145    0.000    0.233    0.000 sre_parse.py:217(__init__)\n",
      "  1102830    0.213    0.000    0.213    0.000 <ipython-input-32-308f8216e1f8>:6(<genexpr>)\n",
      "    50084    0.195    0.000    0.195    0.000 <ipython-input-56-6db5f5ee7e3e>:30(<dictcomp>)\n",
      "   100168    0.111    0.000    0.164    0.000 random.py:220(_randbelow)\n",
      "    89666    0.098    0.000    0.111    0.000 sre_parse.py:797(fix_flags)\n",
      "        1    0.018    0.018    0.109    0.109 <ipython-input-44-3e740ef01568>:7(<setcomp>)\n",
      "   171350    0.107    0.000    0.107    0.000 sre_parse.py:105(__init__)\n",
      "   171350    0.088    0.000    0.107    0.000 sre_parse.py:276(tell)\n",
      "    89666    0.102    0.000    0.102    0.000 {built-in method _sre.compile}\n",
      "   245052    0.080    0.000    0.102    0.000 sre_parse.py:153(__len__)\n",
      "    38126    0.095    0.000    0.100    0.000 sre_compile.py:391(_generate_overlap_table)\n",
      "   179332    0.076    0.000    0.096    0.000 sre_compile.py:513(isstring)\n",
      "     7902    0.016    0.000    0.091    0.000 <ipython-input-44-3e740ef01568>:19(repetitions)\n",
      "    89666    0.085    0.000    0.085    0.000 sre_parse.py:70(__init__)\n",
      "   179332    0.064    0.000    0.082    0.000 sre_parse.py:75(groups)\n",
      "   636500    0.062    0.000    0.062    0.000 {method 'random' of '_random.Random' objects}\n",
      "     7902    0.047    0.000    0.061    0.000 <ipython-input-44-3e740ef01568>:24(<setcomp>)\n",
      "   171350    0.048    0.000    0.048    0.000 sre_parse.py:242(match)\n",
      "    76784    0.047    0.000    0.047    0.000 <ipython-input-34-656b8fb485f1>:7(<setcomp>)\n",
      "   123976    0.042    0.000    0.042    0.000 {method 'getrandbits' of '_random.Random' objects}\n",
      "   246020    0.028    0.000    0.028    0.000 {built-in method builtins.ord}\n",
      "    81684    0.023    0.000    0.023    0.000 sre_parse.py:161(__setitem__)\n",
      "        1    0.003    0.003    0.022    0.022 <ipython-input-44-3e740ef01568>:6(<setcomp>)\n",
      "    76384    0.022    0.000    0.022    0.000 {method 'extend' of 'list' objects}\n",
      "     2433    0.006    0.000    0.016    0.000 <ipython-input-2-f601ec24f6b0>:56(dotify)\n",
      "    89666    0.016    0.000    0.016    0.000 {method 'items' of 'dict' objects}\n",
      "     7902    0.014    0.000    0.014    0.000 <ipython-input-44-3e740ef01568>:23(<listcomp>)\n",
      "    61211    0.012    0.000    0.012    0.000 {method 'endswith' of 'str' objects}\n",
      "   100168    0.011    0.000    0.011    0.000 {method 'bit_length' of 'int' objects}\n",
      "    50084    0.009    0.000    0.009    0.000 {method 'pop' of 'dict' objects}\n",
      "    49204    0.009    0.000    0.009    0.000 {method 'get' of 'dict' objects}\n",
      "     2433    0.006    0.000    0.009    0.000 <ipython-input-2-f601ec24f6b0>:59(<setcomp>)\n",
      "      176    0.008    0.000    0.008    0.000 {method 'clear' of 'dict' objects}\n",
      "       98    0.001    0.000    0.002    0.000 <ipython-input-50-5391d2372e48>:3(subparts)\n",
      "     9029    0.002    0.000    0.002    0.000 {method 'startswith' of 'str' objects}\n",
      "     6431    0.002    0.000    0.002    0.000 <ipython-input-2-f601ec24f6b0>:61(replacements)\n",
      "     3568    0.001    0.000    0.001    0.000 <ipython-input-50-5391d2372e48>:5(<genexpr>)\n",
      "        1    0.000    0.000    0.001    0.001 <ipython-input-44-3e740ef01568>:14(pairs)\n",
      "        1    0.001    0.001    0.001    0.001 <ipython-input-44-3e740ef01568>:16(<setcomp>)\n",
      "       10    0.000    0.000    0.000    0.000 {method 'copy' of 'dict' objects}\n",
      "        1    0.000    0.000    0.000    0.000 <ipython-input-30-cf018e1cb457>:3(__init__)\n",
      "        1    0.000    0.000    0.000    0.000 <ipython-input-2-f601ec24f6b0>:73(trivial)\n",
      "        1    0.000    0.000    0.000    0.000 <ipython-input-44-3e740ef01568>:5(<setcomp>)\n",
      "        1    0.000    0.000    0.000    0.000 weakref.py:102(remove)\n",
      "        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "cProfile.run('findregex(adverbs, nouns)', sort='cumulative')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We see that the majority of the time is in `simplify_covers`, and within that, half the time goes to `eliminate_dominated`. That gives us some ideas of where speedups could be made, but gains will be harder now than before."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "\n",
    "# Speculating: Other Ideas\n",
    "\n",
    "I'm going to stop here, but I'll briefly mention some other ideas that I didn't get to investigate.  Perhaps you can play with some of these, or with other ideas.\n",
    "\n",
    "- *Completely different approach*: [Thomas Breuel](https://plus.google.com/118190679520611168174/posts) suggested doing [minimization](http://en.wikipedia.org/wiki/DFA_minimization) of [weighted finite state transducers](http://nbviewer.ipython.org/url/nlpa.iupr.com/resources/nlpa-openfst.ipynb?attredirects=0&create=1).\n",
    "- *Character classes*: We never considered character classes, such as `'[abc]'`. It is not obvious they would help, but it is possible.  Consider the fragment `'ld|la'`, which shows up in one of the solutions.  We could replace that with a single component, `'l[da]'`.  But we haven't gained anything; both are 5 characters long.  If we had had `'l.d|l.c|l.b|l.a'` then the replacement `'l.[a-d]'` would save 8 characters, but I don't see many opportunities like that.  It might also be possible to use *negative* character classes, like `l[^y]` to explicitly avoid something in the losers set.\n",
    "\n",
    "- *Prefilter parts*: Currently, `regex_covers` generates a huge set of components, then eliminates the ones that match losers (or don't match winners), and then eliminates the ones that are dominated.  We could make `regex_covers` faster by not generating components that can't possibly contribute.  Suppose we're considering a subpart, say `'ab'`. If it matches no losers, then there is no reason to extend it to a longer subpart, such as `'abc'`, because we know that `'abc'` is dominated by `'ab'`.  By filtering out dominated parts before we have to check them, I estimate we should be able to cut the time for `regex_covers` in half, maybe better.\n",
    "- *Better component choice*: We pick the \"best\" component based on how many winners it covers and how many characters it takes.  Maybe we could have a better measure; perhaps taking into account whether it covers winners that are \"easy\" to cover by other regexes, or \"hard\" to cover.\n",
    "- *Tuning*: We have the two parameters `K` and `F`, which are randomly chosen from a fairly arbitrary distribution.  We could measure which values of the parameters perform better and pick those values more often.\n",
    "- *Post-editing*: We concentrated on the task of generating a solution from scratch; another task is to improve an existing solution.  For example, take the set of components in a solution, and see if one component could be dropped&mdash;it is possible that all the winners covered by that component might accidentally have been covered by other components, making it unnecessary. Or take all pairs of components, and see if they could be replaced by a shorter set of components.\n",
    "- *Better bounds*: Branch and Bound search works best if the bounds are tight.  If we can recognize early that the path we are on cannot possibly be as good as the best solution found so far then we can cut off search early and save time.  But the bound estimate we are using now is a poor one.  We estimate the cost of a solution as the cost of the partial solution plus the cost of the shortest component remaining.  We use this estimate because all we know for sure is that we need at least one more component.  Here's one way to get a better bound by recognizing that in many cases we will need more than one more component. We'll define the following quantities:\n",
    "\n",
    "    + *P* = the length of the partial solution, plus the \"|\", if needed.  So if the partial solution is `None`, then *P* = 0, else *P* is the length plus 1.\n",
    "    + *S* = the length of the shortest regex component in `covers`.\n",
    "    + *W* = the number of winners still in `covers`.\n",
    "    + *C* = the largest number of winners covered by any regex in `covers`.\n",
    "    \n",
    "    The current estimate is *P* + *S*.  We can see that a better estimate is *P* + *S* &times; ceil(*W* / *C*).\n",
    "\n",
    "\n",
    "I hope you had fun seeing how I (and Stefan) attacked this problem; now go out and solve some problems of your own."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "\n",
    "\n",
    "<hr>\n",
    "[*Peter Norvig*](http://norvig.com),  Feb. 2014"
   ]
  }
 ],
 "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.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
