Before you run it, say out loud what it will print. Then open the answer.
What it prints
2
4
Balance a stack.
stack = []
for ch in "(()":
if ch == "(":
stack.append(ch)
else:
stack.pop()
print(len(stack))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
1
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
The structure holding data decides which operations are cheap. A set buys membership, a heap buys the next best.
1list the operations
↓
2pick the structure
↓
3check the space cost
↓
4confirm the classes
Line by line
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
a = [1, 2, 3, 4]sets nothing on screen
s = set(a)sets nothing on screen
print(len(s), 3 in s)4 True
Why this worksStructure is cost
Choosing where data lives decides which operations are one step and which are a scan. That choice is a cost decision.
Match the tool to the use
A set for membership, a dict for keys, a sorted list for ranges, a heap for the next best, a stack for nesting.
Examples
List versus set
a = [1, 2, 3, 4]
s = set(a)
print(len(s), 3in s)
Membership is linear in a list and constant on average in a set. The set costs extra space.
Dict for keys
d = {"a": 1, "b": 2}
print(d["b"])
A dict looks up a key in one step on average. That is the tool for counting and grouping.
Sorted list for ranges
a = [1, 4, 7, 9]
lo, hi = 0, len(a) - 1while lo < hi:
mid = (lo + hi) // 2if a[mid] < 5:
lo = mid + 1else:
hi = mid
print(a[lo])
A sorted list answers range questions in log n. That is the structure for nearest and between.