IFI 8410 — Session 11: Search and Hashing
What a lookup costs, and how that cost grows
The problem
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.
And how does that cost grow as the data grows?
So that the lookups I need are cheap.
One exact key, everything between two values, and what is missing are different questions.
The tools
| Tool | Purpose | What it gives you |
|---|---|---|
list | an ordered sequence | x in items, .index(x), .count(x): all of them scan |
sorted, .sort | ordering | a sorted copy or an in-place sort, by any key |
bisect | searching sorted lists | where a value is, or would go, in about log₂(n) steps |
dict | lookup by key | a value stored under a key, found in about one step |
set | membership | "is it there?" in about one step; unions, intersections, differences |
Counter, defaultdict | tallies and groups | counting 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
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)Concept 2
| Case | Comparisons, n items |
|---|---|
| the target is first | 1 |
| it is there, on average | about n / 2 |
| it is not there | n, every time |
Ten times the list, ten times the work: linear. It needs nothing from the data.
for order in orders: # a million
if order["customer"] in customer_list:
... # scans 100,000Up 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 -1low and high.| Items | Linear | Binary |
|---|---|---|
| 1,000 | 500 | 10 |
| 1,000,000 | 500,000 | 20 |
| 1,000,000,000 | 500,000,000 | 30 |
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
On an unsorted list it throws away the half that holds the target and reports "not there". No error.
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
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) % bucketsA lookup takes about one step, whatever the size. Work that does not grow is constant.
Concept 4, continued
dict and set are hash tables999_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 loopIts 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.
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
| Operation | Unsorted list | Sorted list | dict / set |
|---|---|---|---|
| is this key here? | n | log n | 1 |
| add an item | 1 | n | 1 |
| everything between a and b | n | log n | n |
| the smallest; the next larger | n | 1; log n | n |
| needs | nothing | sorting; comparable items | immutable keys; more memory |
dict or a set. The usual case and the usual fix.bisect.in are fine.Worked example — notebook 2
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.
linear
About a quarter of an hour.
binary
Under a second.
hash
A quarter of a second.
Worked example — notebook 2
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))
How many names start with "Star"? How many tips were written in 2019? Two binary searches and a subtraction.
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 monthly report that used to take seconds now takes an hour. The customer file grew from five thousand to five hundred thousand rows.
in against a list, inside a loopfor order in orders:
if order["customer"] in customer_list:
...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
dict and set are hash tables.Now: hands-on
Folder 11-Search-Hashing — work them in this order:
Concepts
Counting comparisons, linear and binary search, a hash table from scratch, and choosing. Four exercises.
Worked example
900,000 tips matched to their businesses three ways, in seven steps. Run it on ARC.
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

