
Code
Algorithmic Wins
The biggest speedups usually come from a better algorithm, not clever tricks. Know the cost of everyday operations:
| Operation | Cost |
|---|---|
x in a_list |
scans every item: O(n) |
x in a_set / key in a_dict |
hash lookup: O(1) on average |
a_list.pop(0) |
shifts every item: O(n). Use collections.deque |
s += piece in a loop |
can copy the string each time. Use "".join(pieces) |
A check like x in b inside a loop over a costs len(a) × len(b).
With 10,000 items each, that's 100 million comparisons. Turn b into a
set once, and it drops to about 10,000 quick lookups:
allowed = set(b) # build once: O(n)
hits = [x for x in a if x in allowed]
Assignment
Both functions give correct answers but are slow. Rewrite them with
sets. (The tests count how many == comparisons your code makes, so
they can tell a set lookup from a list scan.)
common_visitors(a, b): the names inathat also appear inb, ina's order.first_repeat(names): the first name that appears a second time (scanning left to right), orNone.
Both functions give correct answers but are slow. Rewrite them with
sets. (The tests count how many == comparisons your code makes, so
they can tell a set lookup from a list scan.)
common_visitors(a, b): the names inathat also appear inb, ina's order.first_repeat(names): the first name that appears a second time (scanning left to right), orNone.
main.py Python sleeping
Press Run to try your code, then Check to test it.