Advanced · 15 min
Efficient search
Use data shape and algorithm choice to avoid unnecessary work.
Choose constant-time membership
Set membership is designed for fast lookup. Build the set once when you will perform repeated checks.
allowed = {"read", "write"}
print("write" in allowed)
print("delete" in allowed)Output
True False
Search sorted data
Binary search repeatedly discards half of a sorted range. bisect_left returns the position where a value belongs.
from bisect import bisect_left
numbers = [2, 5, 8, 12]
position = bisect_left(numbers, 8)
print(position)Output
2
Efficient search
- Read both efficient search examples before answering.
- Run the task, compare its exact output, and revise the code if needed.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Check a sorted catalog
Complete contains so it uses bisect_left and returns whether target exists in sorted_items. Display True and False for the supplied calls.
Check that the returned position is inside the list before reading it.