*Peter Norvigwith Stefan PochmannFebruary 2014*

![](http://imgs.xkcd.com/comics/regex_golf.png)

Last month I demonstrated a simple Regex Golf program. I thought that was the end of the topic, but Stefan Pochmann sent me a series of emails suggesting some impressive improvements. (Davide Canton and Thomas Breuel also had good suggestions.) So this post is an exploration of some of Stefan's new ideas, and some of my own. I'll try to show how to think about solving a problem, and how to use exploratory programming to test out ideas.

To review, here's the program from part 1 (with minor modifications):

In [1]:

```
import re
from __future__ import division
from __builtin__ import any, all, sum # (because ipython imports the numpy versions)
def verify(regex, winners, losers):
"Return true iff the regex matches all winners but no losers."
missed_winners = {W for W in winners if not re.search(regex, W)}
matched_losers = {L for L in losers if re.search(regex, L)}
if missed_winners:
print "Error: should match but did not:", ', '.join(missed_winners)
if matched_losers:
print "Error: should not match but did:", ', '.join(matched_losers)
return not (missed_winners or matched_losers)
def findregex(winners, losers):
"Find a regex that matches all winners but no losers (sets of strings)."
# Make a pool of regex components, then pick from them to cover winners.
# On each iteration, add the 'best' component to 'solution',
# remove winners covered by best, and keep in 'pool' only components
# that still match some winner.
pool = regex_components(winners, losers)
solution = []
def score(r): return 4 * len(matches(r, winners)) - len(r)
while winners:
best = max(pool, key=score)
solution.append(best)
winners = winners - matches(best, winners)
pool = {r for r in pool if matches(r, winners)}
return OR(solution)
def matches(regex, strings):
"Return a set of all the strings that are matched by regex."
return {s for s in strings if re.search(regex, s)}
OR = '|'.join # Join a sequence of strings with '|' between them
def regex_components(winners, losers):
"Return components that match at least one winner, but no loser."
wholes = {'^'+winner+'$' for winner in winners}
parts = {d for w in wholes for s in subparts(w) for d in dotify(s)}
return wholes | {p for p in parts if not matches(p, losers)}
def subparts(word):
"Return a set of subparts of word, consecutive characters up to length 4."
return set(word[i:i+n] for i in range(len(word)) for n in (1, 2, 3, 4))
def dotify(part):
"Return all ways to replace a subset of chars in part with '.'."
if part == '':
return {''}
else:
return {c+rest for rest in dotify(part[1:])
for c in replacements(part[0])}
def replacements(char):
"Return replacement characters for char (char + '.' unless char is special)."
if (char == '^' or char == '$'):
return char
else:
return char + '.'
def words(text):
"Return a set of all words in the text, lowercased."
return frozenset(text.lower().split())
def phrases(text, sep='/'):
"Return a set of all 'sep'-separated phrases in text, uppercased."
return frozenset(line.strip() for line in text.upper().split(sep))
```

In [2]:

```
winners = words('''washington adams jefferson jefferson madison madison monroe
monroe adams jackson jackson van-buren harrison polk taylor pierce buchanan
lincoln lincoln grant grant hayes garfield cleveland harrison cleveland mckinley
mckinley roosevelt taft wilson wilson harding coolidge hoover roosevelt
roosevelt roosevelt roosevelt truman eisenhower eisenhower kennedy johnson nixon
nixon carter reagan reagan bush clinton clinton bush bush obama obama''')
losers = words('''clinton jefferson adams pinckney pinckney clinton king adams
jackson adams clay van-buren van-buren clay cass scott fremont breckinridge
mcclellan seymour greeley tilden hancock blaine cleveland harrison bryan bryan
parker bryan roosevelt hughes cox davis smith hoover landon wilkie dewey dewey
stevenson stevenson nixon goldwater humphrey mcgovern ford carter mondale
dukakis bush dole gore kerry mccain romney''') - winners
boys = words('jacob mason ethan noah william liam jayden michael alexander aiden')
girls = words('sophia emma isabella olivia ava emily abigail mia madison elizabeth')
nfl_in = words('colts saints chargers 49ers seahawks patriots panthers broncos chiefs eagles bengals packers')
nfl_out = words('''jets dolphins bills steelers ravens browns titans jaguars texans raiders cowboys giants
redskins bears lions vikings falcons buccaneers cardinals rams''')
pharma = words('lipitor nexium plavix advair ablify seroquel singulair crestor actos epogen')
cities = words('paris trinidad capetown riga zurich shanghai vancouver chicago adelaide auckland')
foo = words('''afoot catfoot dogfoot fanfoot foody foolery foolish fooster footage foothot footle footpad footway
hotfoot jawfoot mafoo nonfood padfoot prefool sfoot unfool''')
bar = words('''Atlas Aymoro Iberic Mahran Ormazd Silipan altared chandoo crenel crooked fardo folksy forest
hebamic idgah manlike marly palazzi sixfold tarrock unfold''')
nouns = words('''time year people way day man thing woman life child world school
state family student group country problem hand part place case week company
system program question work government number night point home water room
mother area money story fact month lot right study book eye job word business
issue side kind head house service friend father power hour game line end member
law car city community name president team minute idea kid body information
back parent face others level office door health person art war history party result
change morning reason research girl guy moment air teacher force education''')
adverbs = words('''all particularly just less indeed over soon course still yet before
certainly how actually better to finally pretty then around very early nearly now
always either where right often hard back home best out even away enough probably
ever recently never however here quite alone both about ok ahead of usually already
suddenly down simply long directly little fast there only least quickly much forward
today more on exactly else up sometimes eventually almost thus tonight as in close
clearly again no perhaps that when also instead really most why ago off
especially maybe later well together rather so far once''') - nouns
verbs = words('''ask believe borrow break bring buy can be able cancel change clean
comb complain cough count cut dance draw drink drive eat explain fall
fill find finish fit fix fly forget give go have hear hurt know learn
leave listen live look lose make do need open close shut organise pay
play put rain read reply run say see sell send sign sing sit sleep
smoke speak spell spend stand start begin study succeed swim take talk
teach tell think translate travel try turn off turn on type understand
use wait wake up want watch work worry write''') - nouns
randoms = frozenset(vars(random))
builtins = frozenset(vars(__builtin__)) - randoms
starwars = phrases('''The Phantom Menace / Attack of the Clones / Revenge of the Sith /
A New Hope / The Empire Strikes Back / Return of the Jedi''')
startrek = phrases('''The Wrath of Khan / The Search for Spock / The Voyage Home /
The Final Frontier / The Undiscovered Country / Generations / First Contact /
Insurrection / Nemesis''')
dogs = phrases(''''Labrador Retrievers / German Shepherd Dogs / Golden Retrievers / Beagles / Bulldogs /
Yorkshire Terriers / Boxers / Poodles / Rottweilers / Dachshunds / Shih Tzu / Doberman Pinschers /
Miniature Schnauzers / French Bulldogs / German Shorthaired Pointers / Siberian Huskies / Great Danes /
Chihuahuas / Pomeranians / Cavalier King Charles Spaniels / Shetland Sheepdogs / Australian Shepherds /
Boston Terriers / Pembroke Welsh Corgis / Maltese / Mastiffs / Cocker Spaniels / Havanese /
English Springer Spaniels / Pugs / Brittanys / Weimaraners / Bernese Mountain Dogs / Vizslas / Collies /
West Highland White Terriers / Papillons / Bichons Frises / Bullmastiffs / Basset Hounds /
Rhodesian Ridgebacks / Newfoundlands / Russell Terriers / Border Collies / Akitas /
Chesapeake Bay Retrievers / Miniature Pinschers / Bloodhounds / St. Bernards / Shiba Inu / Bull Terriers /
Chinese Shar-Pei / Soft Coated Wheaten Terriers / Airedale Terriers / Portuguese Water Dogs / Whippets /
Alaskan Malamutes / Scottish Terriers / Australian Cattle Dogs / Cane Corso / Lhasa Apsos /
Chinese Crested / Cairn Terriers / English Cocker Spaniels / Dalmatians / Italian Greyhounds /
Dogues de Bordeaux / Samoyeds / Chow Chows / German Wirehaired Pointers / Belgian Malinois /
Great Pyrenees / Pekingese / Irish Setters / Cardigan Welsh Corgis / Staffordshire Bull Terriers /
Irish Wolfhounds / Old English Sheepdogs / American Staffordshire Terriers / Bouviers des Flandres /
Greater Swiss Mountain Dogs / Japanese Chin / Tibetan Terriers / Brussels Griffons /
Wirehaired Pointing Griffons / Border Terriers / English Setters / Basenjis / Standard Schnauzers /
Silky Terriers / Flat-Coated Retrievers / Norwich Terriers / Afghan Hounds / Giant Schnauzers / Borzois /
Wire Fox Terriers / Parson Russell Terriers / Schipperkes / Gordon Setters / Treeing Walker Coonhounds''')
cats = phrases('''Abyssinian / Aegean cat / Australian Mist / American Curl / American Bobtail /
American Polydactyl / American Shorthair / American Wirehair / Arabian Mau / Asian / Asian Semi-longhair /
Balinese / Bambino / Bengal / Birman / Bombay / Brazilian Shorthair / British Shorthair / British Longhair /
Burmese / Burmilla / California Spangled Cat / Chantilly/Tiffany / Chartreux / Chausie / Cheetoh /
Colorpoint Shorthair / Cornish Rex / Cymric / Cyprus cat / Devon Rex / Donskoy or Don Sphynx / Dragon Li /
Dwelf / Egyptian Mau / European Shorthair / Exotic Shorthair / German Rex / Havana Brown / Highlander /
Himalayan-Colorpoint Persian / Japanese Bobtail / Javanese / Khao Manee / Korat / Korn Ja /
Kurilian Bobtail / LaPerm / Maine Coon / Manx / Mekong bobtail / Minskin / Munchkin / Nebelung / Napoleon /
Norwegian Forest Cat / Ocicat / Ojos Azules / Oregon Rex / Oriental Bicolor / Oriental Shorthair /
Oriental Longhair / Persian / Peterbald / Pixie-bob / Ragamuffin / Ragdoll / Russian Blue / Russian Black /
Sam Sawet / Savannah / Scottish Fold / Selkirk Rex / Serengeti cat / Serrade petit / Siamese / Siberian /
Singapura / Snowshoe / Sokoke / Somali / Sphynx / Swedish forest cat / Thai / Tonkinese / Toyger /
Turkish Angora / Turkish Van / Ukrainian Levkoy / York Chocolate Cat''')
```

And here we show how it works:

In [3]:

```
findregex(starwars, startrek)
```

Out[3]:

In [4]:

```
verify(' T|E.P| N', starwars, startrek)
```

Out[4]:

To improve the program, I'll take the following steps:

*Profiling:*Figure out where the program spends its time.*Speedup:*Make the program faster.*Benchmarking:*Run the program over pairs of arbitrary lists to see how fast it is and how short the solutions are.*Studying:*Learn something by looking at the benchmark results.*Searching:*Introduce a better search algorithm.*Eliminating Components:*Get rid of components that can't possibly be part of an optimal solution.*Adding Components:*Add new types of components to allow new, shorter solutions.*Randomizing Search:*Randomness allows us to explore different parts of the search space.*Speculating:*Think about what we could do next.

Let's see how long it takes to separate the top 100 adverbs from top 100 nouns. We can use iPython's magic incantation `%time`

:

In [5]:

```
%time findregex(adverbs, nouns)
```

Out[5]:

`cProfile`

module to see where the time goes:

In [6]:

```
import cProfile
cProfile.run('findregex(adverbs, nouns)', sort='cumulative')
```

We can see that about 99% of the cumulative time was spent in `matches`

. And 85% of the time in `matches`

goes to calling `re.search`

. So my first thoughts are:

- Can we make each call to
`matches`

run faster? - Can we make fewer calls to
`matches`

? - Can we use
`re.search`

more effectively? - Nothing else matters. 99% of the time is in
`matches`

; don't waste effort speeding up anything else.

Here's one way to use `re.search`

more effectively (and thus make `matches`

faster): 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, which is then called. If you need to search many times with the same regex, then it is faster to call `re.compile`

(and then call the `search`

method on the compiled object), rather than calling `re.search`

.

One thing to be careful of: the `re`

module manages a cache of recent compilations. When we do our timing measurements we will call `re.purge()`

first to clear the cache, to make sure that we don't get misleading time measurements (because some of the regex-compilation work was already done by a previous match).

In [7]:

```
def matches(regex, strings):
"Return a set of all the strings that are matched by regex."
searcher = re.compile(regex).search
return {s for s in strings if searcher(s)}
```

In [8]:

```
re.purge();
%time findregex(adverbs, nouns)
```

Out[8]:

*That was twice as fast!* Not bad for adding one line.

Here's one thing about optimizing Python code that is not an issue with, say, C code: there is overhead in executing Python statements, because they go through the Python byte code interpreter. There is no such overhead for the built-in functions (which are written in C), so it often is faster to replace statement logic with built-in functions. We can compare `{s for s in strings if searcher(s)}`

with a call to the built-in function `filter`

. Here I will use `%timeit%`

which runs the statement repeatedly in a loop, repeats the loop 3 times, and reports the resulting best time:

In [9]:

```
searcher = re.compile('^a.o').search
strings = adverbs
%timeit {s for s in strings if searcher(s)}
%timeit set(filter(searcher, strings))
```

So `filter`

is about 18% faster. We'll keep it:

In [10]:

```
def matches(regex, strings):
"Return a set of all the strings that are matched by regex."
searcher = re.compile(regex).search
return set(filter(searcher, strings))
```

In [11]:

```
re.purge();
%time findregex(adverbs, nouns)
```

Out[11]:

I've run out of ways to make an individual call to `matches`

faster, so let's try to make fewer matches.

`matches`

Against Losers¶I will start by minimizing the number of matches against `losers`

. In `regex_components`

, 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. We could do something like this:

```
def matches_any(regex, strings):
searcher = re.compile(regex).search
return any(searcher(s) for s in strrings)
```

But Stefan Pochmann came up with a better idea. If we concatenate the list of losers together into one big string, then we can call `re.search`

*only once* (for each part `p`

) on that big string. If a part matches the big string anywhere, the call will return immediately, and we will know the part is no good. We have effectively moved the work from Python statements into a builtin function, which should be faster (but we will measure to be sure).

There is one catch: because we allow `'^'`

and `'$'`

in our regex parts, we'll have to arrange 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 to say that `'^'`

and `'$'`

match at newlines. (See the `re`

module documentation if this is unfamiliar.)

Here it is, with before-and-after timing:

In [12]:

```
%timeit re.purge(); regex_components(winners, losers)
```

In [13]:

```
def regex_components(winners, losers):
"Return components that match at least one winner, but no loser."
losers_str = '\n'.join(losers)
def no_losers(part): return not re.compile(part, re.MULTILINE).search(losers_str)
wholes = {'^'+winner+'$' for winner in winners}
parts = {d for w in wholes for p in subparts(w) for d in dotify(p)}
return wholes | set(filter(no_losers, parts))
```

In [14]:

```
%timeit re.purge(); regex_components(winners, losers)
```

`matches`

Against Winners¶Here's what `findregex`

currently looks like:

In [15]:

```
def findregex(winners, losers):
"Find a regex that matches all winners but no losers (sets of strings)."
# Make a pool of regex components, then pick from them to cover winners.
# On each iteration, add the 'best' component to 'solution',
# remove winners covered by best, and keep in 'pool' only components
# that still match some winner.
pool = regex_components(winners, losers)
solution = []
def score(r): return 4 * len(matches(r, winners)) - len(r)
while winners:
best = max(pool, key=score)
solution.append(best)
winners = winners - matches(best, winners)
pool = {r for r in pool if matches(r, winners)}
return OR(solution)
```

Notice that we call `matches`

twice for every component regex in the pool on every iteration of the main loop. If there are 50 iterations of the loop, and 1000 components, that's 100,000 calls to `matches`

. Instead of repeating all these calls, I propose that, for each component regex in the pool, we limit ourselves to this:

- One
`re.compile`

. - One
`re.search`

against each of the winners. - One
`re.search`

against the big string of losers.

How can we make sure we don't repeat searches? By doing the search and *caching* the result. During initialization, we create a dict, which we will call `covers`

, such that `covers[r]`

rerturns the set of all winners that match the regex `r`

. From then on, we look in the dict rather than repeating a search. The new function `regex_covers`

replaces the old function `regex_components`

:

In [16]:

```
def regex_covers(winners, losers):
"""Generate regex components and return a dict of {regex: {winner...}}.
Each regex matches at least one winner and no loser."""
losers_str = '\n'.join(losers)
wholes = {'^'+winner+'$' for winner in winners}
parts = {d for w in wholes for p in subparts(w) for d in dotify(p)}
pool = wholes | parts
searchers = [re.compile(c, re.MULTILINE).search for c in pool]
return {r: set(filter(searcher, winners))
for (r, searcher) in zip(pool, searchers)
if not searcher(losers_str)}
```

`findregex`

to call `regex_covers`

, and replace the global `matches`

function with a local function that looks into the `covers`

cache. Notice that we can't just return the cached set of winners, `covers[r]`

, we have to go through it and find only those elements that are still in the current set of remaining winners.

In [17]:

```
def findregex(winners, losers):
"Find a regex that matches all winners but no losers (sets of strings)."
# Initialize covers = {regex: {winner,...}} for a large set of regex components.
# On each iteration, add the 'best' component to 'solution',
# remove winners covered by best, and keep in 'pool' only components
# that still match some winner.
covers = regex_covers(winners, losers)
pool = set(covers)
solution = []
def matches(r, winners): return {w for w in covers[r] if w in winners}
def score(r): return 4 * len(matches(r, winners)) - len(r)
while winners:
best = max(pool, key=score)
solution.append(best)
winners = winners - covers[best]
pool = {r for r in pool if matches(r, winners)}
return OR(solution)
```

In [18]:

```
re.purge()
%time findregex(adverbs, nouns)
```

Out[18]:

*Wow!* That's approximately 10 times faster than the previous version of `findregex`

, and 20 times faster than the first version! But I don't want to draw too many conclusions from just this one example.

We will benchmark the program on a suite of 20 different problems, and summarize the results. For each problem we'll print the number of characters in the solution, the number of winners covered, the time it took, and the solution. And we'll store solutions in the dict `SOLUTION`

, because it might be useful to have them.

In [19]:

```
import time
ALL = [ # An example has two sets of strings, each with a one-character initial identifying it.
(winners, 'W', 'L', losers),
(boys, 'B', 'G', girls),
(nfl_in, 'I', 'O', nfl_out),
(pharma, 'P', 'C', cities),
(foo, 'F', 'B', bar),
(starwars, 'W', 'T', startrek),
(nouns, 'N', 'A', adverbs),
(nouns, 'N', 'V', verbs),
(randoms, 'R', 'B', builtins),
(dogs, 'D', 'C', cats)]
ALL = [d for datum in ALL for d in (datum, datum[::-1])] # Add in the reverse versions
SOLUTION = {} # Remember solutions; SOLUTION[W, L] will hold a regex
def benchmark(examples=ALL):
"Run examples; print summaries; return total of solution lengths."
total = 0
for (W, Wname, Lname, L) in examples:
re.purge()
t0 = time.time()
solution = SOLUTION[W, L] = findregex(W, L)
t1 = time.time()
assert verify(solution, W, L)
print '%3d ch %3d win %5.2f s %s-%s: %r' % (
len(solution), len(W), t1-t0, Wname, Lname, solution)
total += len(solution)
return total
```

In [20]:

```
%time benchmark()
```

Out[20]:

In 4 seconds we solved twenty problems, getting a score of 1355 for the total number of characters in all the solutions.

(*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.)

What can we do to understand the program better? Can we determine what kinds of regex components are being used? What kinds might we add that are missing? How might we make the program faster? Or allow it to find better solutions?

Let's start by understanding what the regex components look like. Glancing over the output of the benchmark, my impression is that most components are short, in the 2-4 character range. We can be more precise:

In [21]:

```
from collections import Counter, defaultdict
components = [r for solution in SOLUTION.values() for r in solution.split('|')]
Counter(map(len, components)).most_common()
```

Out[21]:

This says that there are 167 components of length 2, etc. We can also view this data as a histogram:

In [22]:

```
hist(map(len, components));
```

In [23]:

```
max(components, key=len)
```

Out[23]:

I happen to own a Havanese, but I don't think the program knew that. Rather, it looks like 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$'`

.

What about the individual characters that make up the components? Which ones are popular? We can see:

In [24]:

```
cat = ''.join
Counter(cat(components)).most_common(20)
```

Out[24]:

I wonder if there are components that appear in many solutions?

In [25]:

```
Counter(components).most_common(20)
```

Out[25]:

I guess not.

Now I want to think about the problem as a set cover problem. Wikipedia shows this diagram to explain set cover:

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.

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 show show some information. We'll list the $N$ "most popular" blue and green dots—the ones with the most links to the other side. Then we'll show histograms of all the nodes and their numbers of links.

But first some explanation: I use the term *multimap* for a dictionary which is a mapping `{key: collection}`

. So `covers`

is a multimap of the form `{regex: {winner,...}}`

. If we apply the function `invert_multimap`

to `covers`

, we get a dict of the form `{winner: {regex, ...}}`

.

In [26]:

```
import matplotlib.pylab as pylab
pylab.rcParams['figure.figsize'] = (8.0, 4.0)
def show(W, L, N=10):
covers = regex_covers(W, L)
inv = invert_multimap(covers)
for ((n1, w), (n2, r)) in zip(top(N, covers), top(N, inv)):
print "%8s %2d | %3d %s" % (w, n1, n2, r)
print "TOTAL %5d | %3d TOTAL" % (len(covers), len(W))
subplot(1, 2, 1); histmm(covers, "regexes", "winners")
subplot(1, 2, 2); histmm(inv, "winners", "regexes")
def top(N, multimap):
"The top N longest items in a dict of {key: {val,...})"
return sorted([(len(vals), key) for (key, vals) in multimap.items()], reverse=True)[:N]
def histmm(multimap, key, val):
"Display a histogram of how many values each key has."
hist(map(len, multimap.values()))
xlabel('set size of {' + val + ',...}')
ylabel('number of ' + key + ' mapping to that size')
def invert_multimap(multimap):
"Covert {key: {val,...}} to {val: [key,...]}."
result = defaultdict(set)
for key in multimap:
for val in multimap[key]:
result[val].add(key)
return result
```

In [27]:

```
show(winners, losers)
```

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 links go in to `'van-buren'`

. (Presumably in large part because the '-' character is unique, so any component containing a '-' will not match any loser.) 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 20 and 110 regexes.

From looking at this I get two ideas:

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*A dominates B*if*A*is shorter and matches a superset of winners. We might as well throw out all dominated regexes right at the start.It might be a good idea to pay special attention to the characters, like

`'-'`

, that appear in the winners but not the losers.

Let's look at another example:

In [28]:

```
show(dogs, cats)
```

My immediate reaction to this is "there are a lot of retrievers and terriers." All ten of the regexes in the table recognize this fact, but almost all the regexes (about 4400 out of 4570) match fewer than 5 dog breeds. In contrast, the right-hand histogram shows that most of the dog breeds have 9 or more regexes that match them.

Let's look at one more example before drawing conclusions:

In [29]:

```
show(adverbs, nouns)
```

The pattern looks similar here. Almost all the regexes match only one winner, but most of the winners are matched by many regexes. What can I conclude from this?

- It would be good to think of new types of regexes that match more winners.
- Most regexes 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.

Given all we've seen, I will shift my attention to understanding the search algorithm we have, and thinking about how to improve it.

`findregex`

is a *greedy search* algorithm. In general, greedy search is used when you are trying to find a solution that consists of components. On each iteration you choose a component that looks good, and you never reconsider that choice; you just keep on adding components until you get a complete solution.

The pseudo-code for a general `greedy_search`

, described as a recursive function, is given below. It takes two arguments: a set of components, and a partial solution indicating components that have previously been chosen. (The invariant condition is that the partial solution plus a solution for the components will always equal a complete solution for the problem.)

```
# Pseudocode
def greedy_search(components, partial_solution=None):
if is_complete(partial_solution):
return partial_solution
else:
best = select_best(components)
return greedy_search(components - best, partial_solution + best)
```

An *exhaustive search* considers *every* possible choice of components, and selects the best solution. On each iteration exhaustive search picks a component (just like greedy search), but then it considers *both* using the component and not using the component. 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.)

```
# Pseudocode
def exhaustive_search(components, partial_solution=None):
if is_complete(partial_solution):
return partial_solution
else:
best = select_best(components)
return min(exhaustive_search(components - best, partial_solution + best),
exhaustive_search(components - best, partial_solution),
key=cost)
```

Here's an interesting piece of trivia: the first thing that this exhaustive search does is a greedy search! Think about it: on each recursive call, `exhaustive_search`

selects the best component, 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* chose the best component.

Here's something else to ponder: why should we bother with selecting the "best" component? If we're going to explore *all* possibilities, wouldn't it be the same if we just selected *any* component, not the "best" one?

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 *R* regex components, then there are $2^R$ subsets of components. Now, we don't have to consider every one of these subsets, because the search ends when we have a complete solution. 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$ components from a pool of $R$, which is math we write as $R \choose W$, or ($R$ choose $W$). For the presidential candidates, we knows that the number of winners, $W$, is 34, and $R$ is 1615.

So exhaustive search would have to consider roughly ${1615} \choose {34}$ = $10^{70}$ combinations, which is clearly too many. Don't even think about dogs versus cats, where $W$ = 100 and $R$ = 4570, so ${4570} \choose {100}$ = $10^{207}$. Fortunately, there is another way.

*Branch and bound* is a search strategy that computes the same result 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:

- The
*branch*part of the name means that, just like exhaustive search, it picks a best component, and considers two branches, one where`best`

is part of the solution, and one where it is not. - 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. - The
*trick*is to notice that the cost of a partial solution always*increases*as we add more components 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 $M$ components left to consider, that means we just eliminated $2^M$ potential combinations all at once. "Eliminating potential combinations" is also called "pruning the seach tree"—"pruning" means cutting off unwanted branches.

The pseudocode below uses a global variable called `SOLUTION`

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 `SOLUTION`

to an improved solution, then the second branch will see that improved value. That is why it is important to choose a good "best" component first—it means we are more likely to find a good solution early on, which makes it more likely that we can prune away branches.

```
# Pseudocode
def branch_and_bound_search(components, partial_solution=None):
if is_complete(partial_solution):
SOLUTION = min(SOLUTION, partial_solution, key=cost)
elif cost(partial_solution) < cost(SOLUTION):
best = select_best(components)
branch_and_bound_search(components - best, partial_solution + best)
branch_and_bound_search(components - best, partial_solution)
else:
pass
return SOLUTION
```

Notice that we don't bother doing the `min`

calculation on the results of the two recursive calls. We know that every time we find a better solution, we will be setting the global variable `SOLUTION`

, so we can just `return SOLUTION`

at the bottom of the function, without worrying about which branch the solution came from.

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? Happily, we know that right at the start the algorithm did the equivalent of a greedy search and set a value for `SOLUTION`

, and that from then on the search is continually updating `SOLUTION`

whenever it finds a better combination. So if at any point we stop the search, we always have some solution. Algorithms that have the property that an answer is always available are called *anytime algorithms*. (Obviously, if you stop the algorithm before it completes you've lost the guarantee of finding the optimal solution.)

I can think of two easy ways to allow early stopping. We could use the `threading.Timer`

class to set up a thread that will 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, we refuse to make any more recursive calls. I'll take this second approach.

Enough pseudocode—here is a real implementation. Since global variables are considered bad style, 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.

In [30]:

```
def findregex(winners, losers, calls=100000):
"Find the shortest disjunction of regex components that covers winners but not losers."
solution = '^(' + OR(winners) + ')$'
covers = regex_covers(winners, losers)
return BranchBound(solution, calls).search(covers)
class BranchBound(object):
"Hold state information for a branch and bound search."
def __init__(self, solution, calls):
self.solution, self.calls = solution, calls
def search(self, covers, partial=None):
"""Recursively extend partial regex until it matches all winners in covers.
Try all reasonable combinations until we run out of calls."""
if self.calls <= 0:
return self.solution
self.calls -= 1
covers, partial = simplify_covers(covers, partial)
if not covers: # Nothing left to cover; solution is complete
self.solution = min(partial, self.solution, key=len)
elif len(OR(partial, min(covers, key=len))) < len(self.solution):
# Try with and without the greedy-best component
def score(c): return 4 * len(covers[c]) - len(c)
best = max(covers, key=score) # Best component
covered = covers[best] # Set of winners covered by best
covers.pop(best)
self.search({c:covers[c]-covered for c in covers}, OR(partial, best))
self.search(covers, partial)
return self.solution
```

There's a new function introduced above, `simplify_covers`

. The idea is that you pass it a `covers`

dict and optionally a partial regex, and it does a triage process to divide the components in `covers`

into three categories:

*Useless components*: could never appear in an optimal solution.*Necessary components*: must appear in any solution (because no other component covers some winner).*Remaining components*: neither useless nor necessary.

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.

`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`

:

In [31]:

```
def simplify_covers(covers, partial=None):
"Eliminate dominated regexes, and select ones that uniquely cover a winner."
previous = None
while covers != previous:
previous = covers
covers = eliminate_dominated(covers)
covers, necessary = select_necessary(covers)
partial = OR(partial, necessary)
return covers, partial
```

`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'])`

In [32]:

```
def OR(*regexes):
"""OR together component regexes. Ignore 'None' components.
Allows both OR(a, b, c) and OR([a, b, c]), similar to max."""
if len(regexes) == 1:
regexes = regexes[0]
return '|'.join(r for r in regexes if r)
```

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 components are dominated? Here's one simple approach: go through each regex component, `r`

, and every time we find one that is not dominated by any another regex component `r2`

, add `r`

(and its winners) to a new dict that we are building up. This approach works, but it is $O(n^2)$.

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, `r`

, one at a time. For each `r`

, compare it only to the regexes, `r2`

, that we have already added to the new dict; if none of them dominate `r`

, then add `r`

. This is still $O(n^2)$, but if, say, 99 out of 100 regexes are eliminated, we will only need $n^2/100$ comparisons.

The code for `eliminate_dominated`

is a slight variant on the version 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, `r`

, in sorted order, if we ever hit an `r`

that covers no winners, then we know that all the remianing `r`

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: in Python the expression `(set2 >= set1)`

means "Is `set2`

a superset of `set1`

?", so the expression `covers[r2] >= covers[r]`

asks if `r2`

covers a superset of the winners that `r`

covers.

In [33]:

```
def eliminate_dominated(covers):
"""Given a dict of {regex: {winner...}}, make a new dict with only the regexes
that are not dominated by any others. A regex r is dominated by r2 if r2 covers
a superset of the matches covered by r, and r2 is shorter."""
newcovers = {}
def signature(r): return (-len(covers[r]), len(r))
for r in sorted(covers, key=signature):
if not covers[r]: break # All remaining r must not cover anything
# r goes in newcache if it is not dominated by any other regex
if not any(covers[r2] >= covers[r] and len(r2) <= len(r)
for r2 in newcovers):
newcovers[r] = covers[r]
return newcovers
```

If some winner is covered by only one component, then we know that component must be part of the solution. The function `select_necessary`

finds all such components, `OR`

s them together, and returns that, along with a dict of the remaining covers, after removing the necessary components (and removing all the winners that are covered by the neccessary components).

In [34]:

```
def select_necessary(covers):
"""Select winners covered by only one component; remove from covers.
Return a pair of (covers, necessary)."""
counts = Counter(w for r in covers for w in covers[r])
necessary = {r for r in covers if any(counts[w] == 1 for w in covers[r])}
if necessary:
covered = {w for r in necessary for w in covers[r]}
covers = {r:covers[r]-covered for r in covers if r not in necessary}
return covers, OR(necessary)
else:
return covers, None
```

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.

In [35]:

```
def test_bb():
assert OR(['a', 'b', 'c']) == OR('a', 'b', 'c') == 'a|b|c'
assert OR(['a|b', 'c|d']) == OR('a|b', 'c|d') == 'a|b|c|d'
assert OR(None, 'c') == 'c'
covers1 = {'a': {'ann', 'abe'}, 'ab': {'abe'}}
assert eliminate_dominated(covers1) == {'a': {'ann', 'abe'}}
assert simplify_covers(covers1) == ({}, 'a')
covers2 = {'a': {'abe', 'cab'}, 'b': {'abe', 'cab', 'bee'},
'c': {'cab', 'cee'}, 'c.': {'cab', 'cee'}, 'abe': {'abe'},
'ab': {'abe', 'cab'}, '.*b': {'abe', 'cab', 'bee'},
'e': {'abe', 'bee', 'cee'}, 'f': {}, 'g': {}}
assert eliminate_dominated(covers2) == simplify_covers(covers2)[0] == {
'c': {'cab', 'cee'}, 'b': {'cab', 'abe', 'bee'}, 'e': {'cee', 'abe', 'bee'}}
covers3 = {'1': {'w1'}, '.1': {'w1'}, '2': {'w2'}}
assert eliminate_dominated(covers3) == {'1': {'w1'}, '2': {'w2'}}
assert simplify_covers(covers3) == ({}, '1|2')
assert select_necessary({'a': {'abe'}, 'c': {'cee'}}) == ({}, 'a|c')
assert {0, 1, 2} >= {1, 2}
assert {1, 2} >= {1, 2}
assert not ({1, 2, 4} >= {1, 3})
return 'test_bb passes'
test_bb()
```

Out[35]:

Let's investigate how much the cover simplification process is helping:

In [36]:

```
covers = regex_covers(winners, losers)
len(covers)
```

Out[36]:

In [37]:

```
covers2, partial = simplify_covers(covers)
len(covers2), partial
```

Out[37]:

In [38]:

```
1 - len(covers2)/len(covers)
```

Out[38]:

We see that `simplify_covers`

gives us a 97% reduction in the number of components!

Now let's do complete benchmarks for branch and bound. I'm going to alter `benchmark`

to print the number of calls taken. The easiest way to do that is to have `findregex`

return the `BranchBound`

object it creates, rather than returning the solution. Since we're changing the signature of `findregex`

, I'll give it a new name, `bb_findregex`

(for "branch and bound `findregex`

").

In [39]:

```
def benchmark(data=ALL, calls=10000):
"Run these data sets; print summaries; return total of solution lengths."
total = 0
for (W, Wname, Lname, L) in data:
re.purge()
t0 = time.time()
bb = bb_findregex(W, L, calls)
t1 = time.time()
SOLUTION[W, L] = bb.solution
assert verify(bb.solution, W, L)
print '{:3d} ch {:3d} win {:6.2f} s {:7,d} calls {}-{}: {!r}'.format(
len(bb.solution), len(W), t1-t0, (calls - bb.calls), Wname, Lname, bb.solution)
total += len(bb.solution)
return total
def bb_findregex(winners, losers, calls=10000):
"Find the shortest disjunction of regex components that covers winners but not losers."
solution = '^(' + OR(winners) + ')$'
bb = BranchBound(solution, calls)
bb.search(regex_covers(winners, losers))
return bb
```

In [40]:

```
%time benchmark(calls=1000)
```

Out[40]:

In [41]:

```
%time benchmark(calls=10000)
```

Out[41]:

Now there are only 3 cases left where we are cutting off search before finding the optimal solution.

In [42]:

```
%time benchmark(calls=100000)
```

Out[42]:

Here's a summary of the total size in characters for all the solutions, and the time taken, for each algorithm:

Algorithm | Size (chars) | Time (secs) |
---|---|---|

Greedy | 1355 | 4 |

BB(1,000) | 1300 | 6 |

BB(10,000) | 1296 | 16 |

BB(100,000) | 1294 | 142 |

We've reached the optimal solution on all but 2 cases, `N-V`

and `D-C`

. It seems like the best path to improvement is not to allow more calls, but rather to sanction additional regex components, hopefully ones that cover more winners in fewer characters.

Following a suggestion by Stefan Pochmann, I will generate a set of regexes of the form `'A.*B'`

where `'A'`

and `'B'`

are any two characters that appear anywhere in any winner, the dot is always the second character, and the third character can be either `'*'`

, `'+'`

, or `'?'`

. I call these `pairs`

.

I will also insert a repetition character (`'*'`

, `'+'`

, or `'?'`

) after every character (except `'^'`

and `'$'`

) in every `part`

. For example, given the part `'a.c'`

, insert either a `'*'`

or a `'+'`

or a `'?'`

after each of the three characters, to get nine new components: `{'a+.c', 'a*.c', 'a?.c', 'a.c+', 'a.*c', 'a.?c', 'a.+c', 'a.c*', 'a.c?'}`

. I call these new components `reps`

.

Here is a new version of `regex_covers`

that adds the new parts (in the sets `pairs`

and `reps`

in lines 8-10):

In [43]:

```
def regex_covers(winners, losers):
"""Generate regex components and return a dict of {regex: {winner...}}.
Each regex matches at least one winner and no loser."""
losers_str = '\n'.join(losers)
wholes = {'^'+winner+'$' for winner in winners}
parts = {d for w in wholes for p in subparts(w) for d in dotify(p)}
chars = set(cat(winners))
pairs = {A+'.'+q+B for A in chars for B in chars for q in rep_chars}
reps = {r for p in parts for r in repetitions(p)}
pool = wholes | parts | pairs | reps
searchers = [re.compile(c, re.MULTILINE).search for c in pool]
return {r: set(filter(searcher, winners))
for (r, searcher) in zip(pool, searchers)
if not searcher(losers_str)}
def repetitions(part):
"""Return a set of strings derived by inserting a single repetition character ('+' or '*' or '?')
after each non-special character. Avoid redundant repetition of dots."""
splits = [(part[:i], part[i:]) for i in range(1, len(part)+1)]
return {A + q + B
for (A, B) in splits
# Don't allow '^*' nor '$*' nor '..*' nor '.*.'
if not (A[-1] in '^$')
if not A.endswith('..')
if not (A.endswith('.') and B.startswith('.'))
for q in rep_chars}
rep_chars = ('*', '+', '?')
```

In [44]:

```
def test_rep():
assert repetitions('a') == {'a+', 'a*', 'a?'}
assert repetitions('ab') == {'a+b', 'a*b', 'a?b',
'ab+', 'ab*', 'ab?'}
assert repetitions('a.c') == {'a+.c', 'a*.c', 'a?.c',
'a.c+', 'a.*c', 'a.?c',
'a.+c', 'a.c*', 'a.c?'}
assert repetitions('^a..d$') == {'^a+..d$', '^a*..d$', '^a?..d$',
'^a..d+$', '^a..d*$', '^a..d?$'}
assert (eliminate_dominated(regex_covers(
{'one', 'on'}, {'won', 'wuan', 'juan'}))
== {'e': {'one'}, '^o': {'on', 'one'}})
return 'test_rep passes'
test_rep()
```

Out[44]:

Let's take our new components out for a spin and see what they can do:

In [45]:

```
findregex(starwars, startrek)
```

Out[45]:

That's pretty cool. Remember, Randall had a 10 character regex in the strip (see below); we previously got it down to 9, but we now have it down to 7 with `' T|P.*E'`

, thanks to the `'P.*E'`

pair.

How much more work are we doing with these additional components? Before, `regex_covers(winners, losers)`

gave 1615 regexes, which were reduced to 49 by `simplify_covers`

. Now:

In [46]:

```
covers = regex_covers(winners, losers)
len(covers)
```

Out[46]:

In [47]:

```
covers, partial = simplify_covers(covers)
len(covers)
```

Out[47]:

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 components.) That's not too bad; let's add *more* components.

Previously we generated regex component parts of length up to 4 characters. Why not say "we're doing 5"? The implementation is easy:

In [48]:

```
subpart_size = 5
def subparts(word):
"Return a set of subparts of word, consecutive characters up to length 5."
return set(word[i:i+1+s] for i in range(len(word)) for s in range(subpart_size))
```

But how many more regex components does this give us?

In [49]:

```
covers = regex_covers(winners, losers)
len(covers)
```

Out[49]:

In [50]:

```
covers, partial = simplify_covers(covers)
len(covers)
```

Out[50]:

In [51]:

```
%time benchmark(calls=1000)
```

Out[51]:

`'^HAVANESE$'`

; instead we have `'H.+N.S'`

, which saves 4 characters, and, look how many breeds it matches:

In [52]:

```
print matches('H.+N.S', dogs)
```

Let's continue benchmarking:

In [53]:

```
%time benchmark(calls=10000)
```

Out[53]:

In [54]:

```
%time benchmark(calls=100000)
```

Out[54]:

Here is the updated summary:

parts@4 | parts@5, reps, pairs | |||
---|---|---|---|---|

Algorithm | Size (chars) | Time (secs) | Size (chars) | Time (secs) |

Greedy | 1355 | 4 | ||

BB(1,000) | 1300 | 6 | 1203 | 170 |

BB(10,000) | 1296 | 16 | 1196 | 184 |

BB(100,000) | 1294 | 142 | 1191 | 348 |

We're making good progress; 1191 characters is a 12% improvement over the 1355 we started with. (On the other hand, it takes almost 100 times longer.)

What next? Add more components? Actually, now I'm more concerned about searching than about components. Let me explain. In the previous benchmark, with fewer components, 100,000 calls were enough to complete the search on all but two cases, so we knew we had the optimal answer given the components, and the only place to go was to add more components.

With `subpart_size = 5`

, we have so many additional components that `benchmark(calls=100000)`

only completes the search half the time. Suppose one of our first choices was wrong, and the search took a component that does not belong in an optimal solution. We might well spend all 100,000 calls on the half of the search tree that keeps the component, never exploring a part of the tree without it. We need to alter the search algorithm to get us out of that rut.

One option is to run the search for a while, then stop it, and run a different search, and hope it 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:

- The '4' in the
`score`

function. That is, vary the tradeoff between number of winners matched and number of characters in a regex. - 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.

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 characters in the component, we will have `score`

add in a random number. We'll call this the "fudge factor" and use the variable `F`

to determine how big it is. If the fudge 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 winner 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.

In [55]:

```
import random
def bb_findregex(winners, losers, calls=10000, restarts=10):
"Find the shortest disjunction of regex components that covers winners but not losers."
solution = '^(' + OR(winners) + ')$'
bb = BranchBoundRandom(solution, calls)
covers = eliminate_dominated(regex_covers(winners, losers))
for restart in range(restarts):
bb.calls = calls
bb.search(covers.copy())
if bb.calls > 0:
return bb # If search was not cut off, then stop
return bb
class BranchBoundRandom(BranchBound):
def search(self, covers, partial=None):
"""Recursively extend partial regex until it matches all winners in covers.
Try all reasonable combinations until we run out of calls."""
if self.calls <= 0:
return partial, covers
self.calls -= 1
covers, partial = simplify_covers(covers, partial)
if not covers: # Nothing left to cover; solution is complete
self.solution = min(partial, self.solution, key=len)
elif len(OR(partial, min(covers, key=len))) < len(self.solution):
# Try with and without the greedy-best component
K = random.choice((2, 3, 4, 4, 5, 6))
F = random.choice((1., 1., 2.))
def score(c): return K * len(covers[c]) - len(c) + random.uniform(0., F)
best = max(covers, key=score) # Best component
covered = covers[best] # Set of winners covered by r
covers.pop(best)
self.search({c:covers[c]-covered for c in covers}, OR(partial, best))
self.search(covers, partial)
return self.solution
```

In [56]:

```
%time benchmark(calls=100)
```

Out[56]:

In [57]:

```
%time benchmark(calls=1000)
```

Out[57]:

In [58]:

```
%time benchmark(calls=10000)
```

Out[58]:

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, then you might know about *negative lookahead assertions* and you could solve `bar`

versus `foo`

like this:

In [59]:

```
solution = '^(?!.*foo)'
verify(solution, bar, foo)
```

Out[59]:

`'^(?!.*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 succeed, else fail." 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`

:

In [60]:

```
def negative_lookahead_solution(W, L):
"Find a solution for W but not L by negative lookahead on SOLUTION[L, W]."
solution = '^(?!.*(' + SOLUTION[L, W] + '))'
assert verify(solution, W, L)
return solution
def better_solution(W, L):
"Return the better of the 'regular' or negative lookahead solutions."
return min(SOLUTION[W, L], negative_lookahead_solution(W, L),
key=len)
%time sum(len(better_solution(W, L)) for (W, _, _, L) in ALL)
```

Out[60]:

parts@4 | parts@5, reps, pairs | |||
---|---|---|---|---|

Algorithm | Size (chars) | Time (secs) | Size (chars) | Time (secs) |

Greedy | 1355 | 4 | ||

BB(1,000) | 1300 | 6 | 1203 | 170 |

BB(10,000) | 1296 | 16 | 1196 | 184 |

BB(100,000) | 1294 | 142 | 1191 | 348 |

BBR(100 × 10) | 1177 | 178 | ||

BBR(1,000 × 10) | 1170 | 193 | ||

BBR(10,000 × 10) | 1165 | 345 | ||

BBR(10,000 × 10) + Neg Look | 1079 | 345 |

In [63]:

```
m = 60.
plot([4/m], [1355], 'gD-', label='Greedy')
plot([170/m, 184/m, 348/m], [1203, 1196, 1191], 'bo-', label='BB')
plot([178/m, 193/m, 345/m], [1177, 1170, 1165], 'rs-', label='BBR')
plot([345/m], [1079], 'k*-', markersize=12, label='BBR + Neg Look')
xlabel('Time (minutes)'); ylabel('Solution size (chars)')
legend(loc='upper right');
```

(This plot gives the total solution length as a function of the amount of computation time.)

We've made great strides, improving the total solution length by 20% over the initial version with greedy search. (It is up to you whether that 20% improvement is worth the increase in time from 4 seconds to 6 minutes.)

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.

*Completely different approach*: Thomas Breuel suggested doing minimization of weighted finite state transducers.*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.*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.*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.*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.*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—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.*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:*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.*S*= the length of the shortest regex component in`covers`

.*W*= the number of winners still in`covers`

.*C*= the largest number of winners covered by any regex in`covers`

.The current estimate is

*P*+*S*. We can see that a better estimate is*P*+*S*× ceil(*W*/*C*).

I hope you had fun seeing how I (and Stefan) attacked this problem; now go out and solve some problems of your own. <p>If you want to download the Python in one file, here it is: xkcd1313.py

<hr>
*Peter Norvig*, Feb. 2014