Boss lesson · Unit 04
Fast Python
Count the operations, then hand the loop to C
What you practise
- How dictionaries and sets find things, built-ins and comprehensions against loops, counting operations, and when to hand the loop to NumPy
Try a question from this lesson
Pick one
The boss problem: make a slow script fast. A list and a set hold the same 1,000,000 ids. You test an id that is in neither. How many stored ids does each compare it with?
Hint
A set is not sorted and does not halve anything. It uses the hash of the value to decide where to look.
Correct answer
list: 1,000,000; set: a few at most
Why
A list has no shortcut: an absent value is compared with every item. A set hashes the value and looks only in the slot that hash leads to, whatever the size. "About 20" would be a binary search, which needs sorted data.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Finding by hash
A dict or set keeps each key in a slot chosen from the key's hash. To find a key, Python hashes it, jumps to that slot and compares only what is there.
The cost barely depends on how many keys are stored. A list has no such shortcut: x in a_list compares item after item.
slots = [None] * 4
for key in (42, 7, 16):
slots[hash(key) % 4] = key
print(slots) # [16, None, 42, 7]
print(slots[hash(42) % 4] == 42) # True11 more exercises in the app
- 5× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.