IFI 8410 — Session 11: Search and Hashing

Finding Things

What a lookup costs, and how that cost grows

The problem

Two programs that look almost identical

if x in collection:
    ...

On a hundred records, any way of answering is instant. On a million, one version looks at up to a million items every time; the other looks at one.

What does a lookup cost?

And how does that cost grow as the data grows?

How should the data be organised?

So that the lookups I need are cheap.

Which organisation fits which question?

One exact key, everything between two values, and what is missing are different questions.

The tools

All of it is in Python itself

ToolPurposeWhat it gives you
listan ordered sequencex in items, .index(x), .count(x): all of them scan
sorted, .sortorderinga sorted copy or an in-place sort, by any key
bisectsearching sorted listswhere a value is, or would go, in about log₂(n) steps
dictlookup by keya value stored under a key, found in about one step
setmembership"is it there?" in about one step; unions, intersections, differences
Counter, defaultdicttallies and groupscounting and grouping, built on dict

pandas uses the same ideas: merge, isin, groupby, value_counts are built on hash tables; searchsorted is a binary search.

Concept 1

Count the work, do not time it

def linear_search(items, target):
    comparisons = 0
    for index in range(len(items)):
        comparisons += 1
        if items[index] == target:
            return (index, comparisons)
    return (-1, comparisons)
  • Time the same line five times and you get five answers; on a shared machine, very different ones.
  • A count of comparisons is the same on every machine.
  • It answers what a time cannot: what happens when the data is ten times larger?

Concept 2

One search

CaseComparisons, n items
the target is first1
it is there, on averageabout n / 2
it is not theren, every time

Ten times the list, ten times the work: linear. It needs nothing from the data.

A search inside a loop

for order in orders:              # a million
    if order["customer"] in customer_list:
        ...                       # scans 100,000

Up to a hundred billion comparisons. Work that grows with the product of two sizes is quadratic.

"Is this new?" and "which are missing?" are questions about things that are not there: the worst case, every time.

Concept 3

def binary_search(items, target):
    low, high = 0, len(items) - 1
    while low <= high:
        middle = (low + high) // 2
        if items[middle] == target:
            return middle
        if items[middle] < target:
            low = middle + 1
        else:
            high = middle - 1
    return -1
  • Guess a number from 1 to 100: nobody starts at 1. Every answer halves what is left.
  • The promise the loop keeps: if the target is in the list, it is between low and high.
ItemsLinearBinary
1,00050010
1,000,000500,00020
1,000,000,000500,000,00030

2²⁰ is about a million. The number of halvings is the logarithm to base 2 of the size: logarithmic work.

Concept 3, two things to know

It needs sorted data, and fails silently

On an unsorted list it throws away the half that holds the target and reports "not there". No error.

Sorting has a price

About n × log₂(n) comparisons, paid once. For one lookup it is a waste; for a few dozen it has already paid for itself.

import bisect

position = bisect.bisect_left(sorted_items, target)       # where it is, or would go
found = position < len(sorted_items) and sorted_items[position] == target

count = bisect.bisect_left(dates, "2020-01-01") - bisect.bisect_left(dates, "2019-01-01")

The insertion point is more useful than "found or not": two of them fence in a range without looking inside it.

Concept 4

Hashing: do not search, compute where it must be

def hash_key(key):
    value = 0
    for character in key:
        value = (value * 31
                 + ord(character)) % 1_000_000_007
    return value

bucket = hash_key(key) % buckets
  • A cloakroom: the last two digits of the ticket are the hook.
  • A hash function turns a key into a number, the same one every time.
  • Two keys in one bucket is a collision, so each bucket holds a short list.
  • The load factor is keys ÷ buckets. Past a limit, the table doubles and re-places every key.

A lookup takes about one step, whatever the size. Work that does not grow is constant.

Concept 4, continued

dict and set are hash tables

999_999 in a_list_of_a_million      # scans
999_999 in a_set_of_a_million       # one step: thousands of times faster

customers = set(customer_list)      # the one-line fix for the slow loop

A key must not change

Its bucket is computed from its contents. Change them and it sits in the wrong bucket, never to be found. So keys are immutable: numbers, strings, tuples. Not lists.

A hash table has no order

The hash scatters keys on purpose. It can say whether exactly this key is present, and nothing about what comes next, lies between, or starts with the same letters.

Concept 5

Choosing

OperationUnsorted listSorted listdict / set
is this key here?nlog n1
add an item1n1
everything between a and bnlog nn
the smallest; the next largern1; log nn
needsnothingsorting; comparable itemsimmutable keys; more memory
  1. Many lookups by exact key: a dict or a set. The usual case and the usual fix.
  2. Questions about order or ranges: sort once, then bisect.
  3. A handful of items, or a single lookup: a list and in are fine.

Worked example — notebook 2

900,000 tips and their businesses

Each tip carries the id of a business; a separate file holds 150,000 businesses. To say anything about a tip, its business has to be found.

Scan the list for each tip

linear

About a quarter of an hour.

Sort the ids once, then halve

binary

Under a second.

A dictionary from id to business

hash

A quarter of a second.

  • The step from the first to the second is the difference between unusable and instant.
  • The step from the second to the third hardly matters.
  • This is the join that databases and pandas perform, and it is why they are fast.

Worked example — notebook 2

What each structure was good for

A set: membership

Which businesses have no tip at all? Does every tip refer to a business we have? How many different people wrote tips? len(set(user_ids))

Sorted data: ranges and prefixes

How many names start with "Star"? How many tips were written in 2019? Two binary searches and a subtraction.

A dictionary: tallies

Which businesses get the most tips? One pass, one running total per key. What Counter, groupby and value_counts do underneath.

Orphan records are a routine data-quality check before trusting any join. With a set it is cheap enough to run every time.

In practice

A slow report, diagnosed

A monthly report that used to take seconds now takes an hour. The customer file grew from five thousand to five hundred thousand rows.

An in against a list, inside a loop

for order in orders:
    if order["customer"] in customer_list:
        ...

One line restores the seconds

customers = set(customer_list)
for order in orders:
    if order["customer"] in customers:
        ...

Recognising that pattern is the most practically useful thing in this session.

To take away

Key points

  • Ask how the work grows, not how long it took today.
  • A linear search is harmless once and ruinous inside a loop.
  • Binary search needs sorted data and is silently wrong without it.
  • A hash table finds an exact key in about one step; dict and set are hash tables.
  • Sorted data answers "between", "next" and "starts with". A hash table does not.
  • Before optimising anything else, look for a scan inside a loop.

Now: hands-on

Over to the notebooks

Folder 11-Search-Hashing — work them in this order:

1Finding Things

Concepts

Counting comparisons, linear and binary search, a hash table from scratch, and choosing. Four exercises.

2Yelp Tips

Worked example

900,000 tips matched to their businesses three ways, in seven steps. Run it on ARC.

3Reference

Look things up

Lists, bisect, dictionaries and sets to keep open while you work.

As you work, ask of every lookup: what happens when the data is ten times larger?
Homework: Homework 10: Three Ways to Find It

◀ Slides