Stacks at work: brackets, undo and expression evaluation
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A stack only lets you touch its top item, and that turns out to be exactly what many real problems need. Feed one stack three different inputs and watch every token hop on or off: a bracket checker that pushes each opener and lets each closer pop its partner, an editor's undo stack, and a calculator that evaluates postfix expressions like 3 4 + 2 *. The Software lesson "Stacks and queues" introduces push and pop with a Python list, and "Linked lists: singly, doubly and circular" shows another way to build one.
Brackets close in reverse
In ([]{}) every closing bracket must match the most recent bracket still open. Most recent first is last in, first out: the rule of a stack. A Python list works as one: append() pushes on top, pop() takes the top off.
input: "([]{})"
rule: a closer must match the newest opener still open
stack = [] # a Python list
stack.append(x) # push x on top
stack.pop() # remove and return the topاقرأ الدرس خطوة بخطوة
Brackets close in reverse
In ([]{}) every closing bracket must match the most recent bracket still open. Most recent first is last in, first out: the rule of a stack. A Python list works as one: append() pushes on top, pop() takes the top off.
input: "([]{})" rule: a closer must match the newest opener still open stack = [] # a Python list stack.append(x) # push x on top stack.pop() # remove and return the topOpeners go on the stack
Read the input left to right. ( is an opener, so line 6 pushes it. [ is an opener too, so it lands on top of (. The stack holds exactly the brackets still waiting for a partner.
balanced("([]{})") stack before: [] ( push ( → ['('] [ push [ → ['(', '[']A closer pops its partner
] is a closer. Line 8 pops the top item and checks that it is the matching opener. The top is [, so the pair is good and both are done. ( still waits underneath.
balanced("([]{})") stack before: ['(', '['] ] pop [: a match → ['(']Only the top is checked
{ is pushed on top of (. Then } pops it: a match. A closer only ever looks at the top of the stack, never deeper, so each character costs one push or one pop.
balanced("([]{})") stack before: ['('] { push { → ['(', '{'] } pop {: a match → ['(']Empty at the end: balanced
) pops (, the last opener. The loop ends and line 10 returns not stack: an empty stack means every opener found its partner, so the answer is True. The work grows in step with the length: O(n).
balanced("([]{})") stack before: ['('] ) pop (: a match → [] loop ends: stack == [] return not stack → TrueTwo ways to fail
In (] the closer ] pops (, the wrong partner, so line 9 returns False. A string like (( fails the other way: the loop ends with ( still on the stack, so not stack is False.
balanced("(]") stack before: [] ( push ( → ['('] ] pop (: wrong partner → return False balanced("((") → False: the loop ends with ['(', '('] still on the stackUndo: every edit is pushed
A text editor uses the same idea. Each time you type, it pushes a note of that edit onto an undo stack. Type c, a, t and the stack holds +c, +a, +t, newest on top.
typing c, a, t, then undo stack before: [] c push +c → ['+c'] a push +a → ['+c', '+a'] t push +t → ['+c', '+a', '+t'] text = "cat"Undo pops the newest edit
Press undo and the editor pops the top edit, +t, and reverses it: the text goes from cat back to ca. Press it again and +a comes off next. Undo always takes back the newest change first.
typing c, a, t, then undo stack before: ['+c', '+a', '+t'] undo pop +t → ['+c', '+a'] text = "cat"[:-1] = "ca"Postfix: numbers wait
In postfix the operator comes after its two numbers: 3 4 + 2 * means (3 + 4) × 2. Numbers are pushed. + pops 4, then 3, adds them and pushes 7.
eval_postfix("3 4 + 2 *".split()) stack before: [] 3 push 3 → [3] 4 push 4 → [3, 4] + pop 4 and 3, push 7 → [7]The last item is the answer
2 is pushed on top of 7. * pops 2, then 7, multiplies and pushes 14. At the end one number is left on the stack: the answer, 14. No brackets or precedence rules were needed.
eval_postfix("3 4 + 2 *".split()) stack before: [7] 2 push 2 → [7, 2] * pop 2 and 7, push 14 → [14] return stack.pop() → 14 (3 + 4) * 2 == 14
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01balanced() reads "{[]}". What is on the stack just after it reads the ] character?
{ and [ are pushed. ] pops the top, [, which is its partner. That leaves { waiting for its own closer.
02Which string makes balanced() return False because openers are left over at the end?
In "(()" the ) pops one (, and the loop ends with ( still on the stack, so not stack is False. "(]" fails too, but because the wrong partner is on top.
03You type x, then y, then z, and press undo twice. Using one undo stack, which edits are left?
The stack holds +x, +y, +z with +z on top. The first undo pops +z and the second pops +y, so only +x is left.
04What does the postfix expression 5 1 2 + * evaluate to?
Push 5, 1 and 2. + pops 2 and 1 and pushes 3. * pops 3 and 5 and pushes 15. It means 5 × (1 + 2).
05Why does balanced() run in O(n) time for a string of n characters?
A closer only checks the top of the stack, never deeper. Python's list append() and pop() from the end are amortized O(1), so n characters cost O(n) in total.
المسرد
- Stack
- A collection where you add and remove items only at one end, the top. The last item in is the first one out (LIFO).
- Push
- Put an item on top of a stack. In Python: stack.append(x).
- Pop
- Remove the top item of a stack and return it. In Python: stack.pop().
- Balanced brackets
- A string in which every closing bracket matches the most recent opening bracket still open, and no opener is left at the end.
- Undo stack
- A stack of the edits a program has made. Undo pops the newest edit and reverses it.
- Postfix notation
- A way to write expressions with each operator after its two operands, so 3 4 + means 3 + 4. It needs no brackets and no precedence rules.
- Operand
- A value an operator works on. In 3 + 4 the operands are 3 and 4.
الملاحظات والمصادر
- The not stack test on line 8 matters: a closer with nothing open, as in ")(", would make pop() on an empty list raise IndexError. Python checks not stack first and stops there, so pop() never runs on an empty list.
- Python list append() and pop() from the end take amortized O(1) time (MIT 6.006, lecture 2), so balanced() and eval_postfix() run in O(n) time for n characters or tokens. In the worst case, such as "((((", the stack grows to n items.
- Order matters for - and /: the first pop gives the right-hand number b, the second gives the left-hand a. So "8 3 -" computes 8 - 3 = 5, not 3 - 8.
- Real editors keep a second stack for redo: undo pops an edit off the undo stack and pushes it onto the redo stack, and a fresh edit clears the redo stack. The figure shows one undo stack and the edits only, not the full text in each note.
- Normal infix expressions with brackets, like (3 + 4) * 2, can be evaluated directly with two stacks, one for numbers and one for operators. That is Dijkstra's two-stack algorithm in Sedgewick and Wayne §1.3.
اختبار يتاح بعد الخطوة الأخيرة.