Bitpath

Boss lesson · Unit 04

Fast Python

Count the operations, then hand the loop to C

13 exercisesabout 3 min

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.

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.

Python
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)  # True

11 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.

One email when Bitpath is ready to try. Nothing else. Privacy