Parse nested brackets, paths and repeat codes, and evaluate infix expressions with precedence and parentheses using stacks.
A payments app lets a merchant type a fee formula, such as 12 + 3 * (4 - 1). The app must work out its value, and say where a bracket is missing. In the same release, your team lead has two more parsing jobs: clean up file paths, and expand repeat codes such as 3[ab].
Your team lead says: "The formula is only text. Make the app read it, and give the same answer as a calculator."
All three jobs read text left to right, and the text has a shape: groups inside groups. The shape decides what must wait. When a group opens, whatever was being read must wait until the group closes, and the newest group closes first. That is a stack.
This lesson reads four shapes: nested brackets, paths, repeat codes and expressions. The tools are the stack from the first lesson, plus a few rules about order.
Picture a set of nesting dolls. To reach the small doll, you open the large doll, then the medium one, then the small one. To put them away, you close them in the opposite order: the small doll first, then the medium doll, then the large doll.
The dolls you have opened and not yet closed are a stack. The one opened last is on top, and it is the only one you can close. In a text, an opening bracket opens a doll and a closing bracket closes the top one.
You open the large doll, then the medium, then the small, and close them in the opposite order. Open dolls are a stack: the newest closes first.
A parsing stack is an ordinary stack. It sits on an array or a linked list, and the parser pushes when a group opens and pops when it closes. What it holds depends on the job: a bracket, a folder name, a saved result.
Step by step: Open brackets on a stack in memory. The animated player loads in your browser.
Five words come up in every parsing problem:
20 - 5 - 3 is (20 - 5) - 3.Predict what happens
Q A calculator reads 2 + 3 * 4. What is its value?
Answer: B
Times has a higher precedence than plus. So 3 * 4 = 12 is worked out first, and then 2 + 12 = 14. Reading strictly from left to right would give 20.
Start with one kind of bracket. Read the marks from left to right, and keep the depth: add 1 for ( and subtract 1 for ). A string is balanced when the depth never goes below 0 and ends at 0. Take (()())().
| Position | Mark | Depth after |
|---|---|---|
| 0 | ( |
1 |
| 1 | ( |
2 |
| 2 | ) |
1 |
| 3 | ( |
2 |
| 4 | ) |
1 |
| 5 | ) |
0 |
| 6 | ( |
1 |
| 7 | ) |
0 |
Step by step: Read ( ( ) ( ) ) with a push for each open bracket and a pop for each close. The animated player loads in your browser.
The deepest point is 2. A stack of open brackets would hold only ( marks, so its size is the depth. When every open item is the same, a counter holds everything the stack would. That is how you remove the outer layer of every group, and count the brackets to add.
If there are several kinds, such as (), [] and {}, the stack must hold the kind, to check that each closing bracket matches the one on top.
Predict what happens
Q You read the marks (()( from left to right and keep a depth. What is the depth after the last mark?
Answer: C
The depth goes 1, 2, then back to 1 at the ), and up to 2 at the last (. Two groups are still open.
Exercise · Put it in order: The depth counter. Arrange the lines into a function that says whether every ( has a matching ). It keeps only a depth, because there is one kind of bracket.
def is_balanced(text):
depth = 0
for ch in text:
if ch == "(":
depth += 1
if ch == ")":
depth -= 1
if depth < 0:
return False
return depth == 0
return depth >= 0A file path is a walk through folders. A name goes down into a folder, and .. goes back up. Read the parts between the slashes, and keep the folders you are inside on a stack.
The rules are exact. An empty part, from the leading slash or a doubled or trailing one, changes nothing. A single . means stay where you are.
A part of exactly two dots pops the last folder, and at the root it does nothing, because the root has no parent. Everything else is a name, even ... or .hidden.
Take the path /a/b/./c/../../d//. Split at every slash, it has ten parts.
| Part | What it is | Action | Stack after |
|---|---|---|---|
| (empty) | empty (before the leading slash) | skip | (empty) |
a |
a name | push | a |
b |
a name | push | a, b |
. |
here | skip | a, b |
c |
a name | push | a, b, c |
.. |
up one level | pop c |
a, b |
.. |
up one level | pop b |
a |
d |
a name | push | a, d |
| (empty) | empty (a doubled or trailing slash) | skip | a, d |
| (empty) | empty (a doubled or trailing slash) | skip | a, d |
Step by step: The path /a/b/../c with folders 1, 2 and 3. The animated player loads in your browser.
The result is /a/d. The folder c went in and came out, the second .. removed b, and d went in under a.
A name pushes a folder, two dots pop it, and at the root two dots do nothing. Here /a/b/../c becomes /a/c.
Predict what happens
Q Which path is the same as /a/b/../c?
Answer: B
The two dots take you back up from b to a. Then c goes in under a, so the path is /a/c.
Exercise · Predict the output: Where does the path end?. The stack reads the parts of a path. Only . and .. are special. What does this print?
stack = []
for part in "/x/./y/../../z/.../w/".split("/"):
if part == "..":
if stack:
stack.pop()
elif part != "" and part != ".":
stack.append(part)
print("/" + "/".join(stack))A repeat code such as 2[x3[y]z] means that x, then 3[y], then z is written twice. The inner group closes first, so the open groups are a stack. Each group needs two facts that must wait: where it started in the text, and its count.
Keep one text buffer. A digit builds the count, one digit at a time, so 1 and then 2 make 12. At [, push the position where the group starts and the count.
A letter goes into the buffer. At ], pop the note. The group is in the buffer once already, so add it count - 1 more times.
| Character | What happens | Text so far | Stack of (start, count) |
|---|---|---|---|
2 |
the count is 2 | (empty) | (empty) |
[ |
push (start 0, count 2) | (empty) | (0, 2) |
x |
add the letter | x |
(0, 2) |
3 |
the count is 3 | x |
(0, 2) |
[ |
push (start 1, count 3) | x |
(0, 2), (1, 3) |
y |
add the letter | xy |
(0, 2), (1, 3) |
] |
pop: y is repeated 3 times in all |
xyyy |
(0, 2) |
z |
add the letter | xyyyz |
(0, 2) |
] |
pop: xyyyz is repeated 2 times in all |
xyyyzxyyyz |
(empty) |
The text is xyyyzxyyyz. The buffer only grows at the end, so the start position of an outer group never moves.
An opening bracket pushes a note: where its group starts, and its count. A closing bracket pops it and repeats the group in place.
Predict what happens
Q The code 3[a2[b]] is decoded. What is the text?
Answer: B
The inner code 2[b] gives bb. The group a followed by bb is abb, and it is written 3 times: abbabbabb.
Now an expression with +, -, * and /. A sum is a list of terms. A + or - starts a new term, and a * or / changes the newest term.
So keep the terms on a stack. A - pushes its number as a negative term. Take 6 + 4 * 3 - 8 / 5, and read the first number as if a + stood in front of it.
An operator finishes the number before it, and the operator that came before that number decides what to do with it. At the end, the value is the sum of the stack.
| Number read | Operator before it | What happens | Terms after |
|---|---|---|---|
| 6 | + |
a new term | 6 |
| 4 | + |
a new term | 6, 4 |
| 3 | * |
multiply the newest term | 6, 12 |
| 8 | - |
a new term, negative | 6, 12, -8 |
| 5 | / |
divide the newest term by 5, toward zero | 6, 12, -1 |
Step by step: The terms of 6 + 4 * 3. The animated player loads in your browser.
The value is 17. The term -8 was divided by 5, and the result was -1.
Plus and minus push a term. Times and divide change the newest term. Division drops the fraction toward zero, so minus 8 divided by 5 is minus 1.
Exercise · Find the bug: The term that never lands. This function reads a sum of products such as 6+4*3, with digits, + and * only and no spaces. It uses a stack of terms. On some inputs the last number is missing from the answer. Which line is wrong?
def calculate(text):
terms = []
num = 0
op = "+"
for i in range(len(text)):
ch = text[i]
if ch.isdigit():
num = num * 10 + int(ch)
if not ch.isdigit() or i == len(text):
if op == "+":
terms.append(num)
else:
terms[-1] *= num
op = ch
num = 0
return sum(terms)The rule for the calculator is to drop the fraction, toward zero. For -8 / 5, the exact value is -1.6, and dropping the fraction gives -1. Languages do not agree on this, and the table shows what each one does, run on the same numbers.
| Language | Expression | Result |
|---|---|---|
| Python | -8 // 5 |
-2: it rounds down |
| Python | int(-8 / 5) |
-1: it truncates, through a float |
| Java | -8 / 5 |
-1: it truncates toward zero |
| C++ | -8 / 5 |
-1: it truncates toward zero |
| JavaScript | Math.floor(-8 / 5) |
-2: it rounds down |
| JavaScript | Math.trunc(-8 / 5) |
-1: it truncates toward zero |
If the stack holds the negative term -8 and Python divides it with //, the total is 16, not 17. The safe way is to divide the size and keep the sign: -(-top // number) when top is negative. Java and C++ truncate on their own.
Exercise · Break it: Find the division that rounds the wrong way. The calculator must drop the fraction, toward zero. This divide function rounds down instead. Find two numbers where it gives the wrong answer.
def divide(a, b):
return a // bOperators of one level go from left to right. 20 - 5 - 3 is (20 - 5) - 3 = 12, and not 20 - (5 - 3) = 18. In the same way, 100 / 10 / 5 is (100 / 10) / 5 = 2, and not 50.
The stack of terms gives this for free. The terms are 20, -5 and -3, and their sum is 12. A single division chain divides the same term twice, 100 to 10 to 2.
| Number read | Operator before it | What happens | Terms after |
|---|---|---|---|
| 20 | + |
a new term | 20 |
| 5 | - |
a new term, negative | 20, -5 |
| 3 | - |
a new term, negative | 20, -5, -3 |
Predict what happens
Q A calculator reads 20 - 5 - 3. What is its value?
Answer: B
The terms are 20, -5 and -3. Minus is left to right, so 20 - 5 = 15, and then 15 - 3 = 12.
Spaces carry no meaning between the parts, so skip them. Do not treat a space as an operator. But a space never splits a number: 12 3 is not in the input.
A - is a subtraction when it comes after a number or a closing bracket. It is a sign, a unary minus, in two places: at the very start of the text, and right after an opening bracket. In -(2 + 3) and in (-4 + 9) the minus belongs to the group or the number after it.
Brackets change the order. Keep the value of the group you are in, and the sign of what comes next. At (, push the result so far and the sign in front of the bracket, and start the group at 0. At ), pop them, and add the group's value to the saved result, times the saved sign.
Take 9 - (2 + (4 - 6)) - (-3 + 5). The table shows one row for each sign or bracket, and digits only build the number. A row's sign stays until the next +, - or ( sets it, so the sign shown after a ) is never used.
| Character | Number finished | Result after | Sign after | Stack of (result, sign) |
|---|---|---|---|---|
- |
9 | 9 | -1 | (empty) |
( |
0 | 0 | +1 | (9, -1) |
+ |
2 | 2 | +1 | (9, -1) |
( |
0 | 0 | +1 | (9, -1), (2, +1) |
- |
4 | 4 | -1 | (9, -1), (2, +1) |
) |
6 | 0 | -1 | (9, -1) |
) |
0 | 9 | -1 | (empty) |
- |
0 | 9 | -1 | (empty) |
( |
0 | 0 | +1 | (9, -1) |
- |
0 | 0 | -1 | (9, -1) |
+ |
3 | -3 | +1 | (9, -1) |
) |
5 | 7 | +1 | (empty) |
| (end) | 0 | 7 | +1 | (empty) |
Step by step: A bracket saves the result so far, and restores it. The animated player loads in your browser.
The value is 7. The minus in front of (2 + (4 - 6)) was saved with the 9, so it was applied to the whole group once. A unary minus, as in (-3 + 5), needs no special rule: it sets the sign of the next number.
An opening bracket saves the result and the sign in front of it. A closing bracket restores them, so a minus flips the whole group.
When there are several precedence levels and brackets at once, use two stacks: one for values and one for operators. When an operator arrives, apply the operators on top while they have the same or a higher precedence. Then push it. A ( is pushed, and a ) applies operators until the (.
Take 2 + 3 * ( 4 - 1 ).
| Token | Values after | Operators after |
|---|---|---|
2 |
2 | (empty) |
+ |
2 | + |
3 |
2, 3 | + |
* |
2, 3 | + * |
( |
2, 3 | + * ( |
4 |
2, 3, 4 | + * ( |
- |
2, 3, 4 | + * ( - |
1 |
2, 3, 4, 1 | + * ( - |
) |
2, 3, 3 | + * |
end |
11 | (empty) |
The value is 11. The * waited on the stack, because the ( after it came first. Its right side was the whole group.
The words "the same or a higher precedence" matter. On 20 - 5 - 3, the second - finds a - on top. Popping on "the same" applies 20 - 5 first and gives 12. Popping only on "higher" leaves both on the stack, and the end applies 5 - 3 first, which gives 18.
Every operation touches the top, so a parsing stack costs what the first lesson said. The new part is the cost of reading a whole text.
| Operation | Stack of open items | Counter (one kind of bracket) | Recursive parser |
|---|---|---|---|
| Push an open item | O(1) | O(1): add 1 | O(1): one more call |
| Pop at the closing item | O(1) | O(1): subtract 1 | O(1): a call returns |
| Peek at the innermost open item | O(1) | Not needed: all alike | O(1): the current call |
| Search: is every bracket matched | O(n), one pass | O(n), one pass | O(n), one pass |
| Read a text of n characters | O(n) | O(n) time, O(1) memory | O(n) time, O(depth) call stack |
| Read any open item below the top | O(k) for the item k places down | Not possible: counts only | O(k) |
All three read the text in one pass. They differ in memory and in limits. A recursive parser keeps its open groups on the call stack, which is limited.
A text nested 50,000 deep fails in each language:
RecursionError at its default limit of 1,000 calls.RangeError.StackOverflowError when the nesting is deeper than its default stack holds. That depth varies from run to run.A stack in your own code has no such limit.
Now drive a parsing stack yourself. A number stands for whatever the job pushes: an open bracket, a folder, a saved result or a term. Use the demos to see each job, and read the step counter.
Try these five, in order:
( and pop for each ) while you read (()()). Where does the stack stop growing?.. removes before you step.4 * 3.)?The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the moves yourself. The lab gives you a RepeatDecoder class. A person types a repeat code a piece at a time, so the decoder must remember its open groups between calls. You write text, open, close, depth, current and decoded.
Each open group is a frame: the text so far, and the count it will be repeated. A frame stack holds them, and the first frame is the top level.
Four rules keep the class correct after every call:
text adds letters to the newest frame, the innermost open group.close repeats the newest frame's text and adds it to the frame below. At the top level there is nothing to close, so it returns false and changes nothing.depth is the number of open groups, and decoded shows only what has been closed.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a stack when the text has groups inside groups, and the innermost group must finish before the one around it. That covers brackets, tags, paths, repeat codes and formulas. A stack reads them in one pass, with a few operations for each character.
If every open item is alike, a counter is enough. If the open items differ, the stack holds what you must restore: a kind, a position, a count or a sign.
Do not write your own parser for a language with many rules, such as a programming language, JSON or HTML. Use a parser built for it. A small stack parser handles brackets, paths and simple formulas, and grows hard to keep correct beyond that.
And do not hand text to a function that runs it, such as eval, to get a value. A formula typed by a user can then run any code. A parser that reads only numbers and four operators is safe by construction.
A stack of terms holds -8, and the next operator is / 5. In Python, top // number gives -2, but the calculator must give -1. On 6 + 4 * 3 - 8 / 5 the total is 16 instead of 17. Divide the size of the number and keep the sign.
Python's // rounds minus 8 / 5 down to minus 2, but the calculator must truncate toward zero to minus 1. The total is 17, not 16.
In the two-stack method, an operator must pop the operators on top that have the same or a higher precedence. If you pop only on a higher one, equal operators pile up and are applied from the right. On 20 - 5 - 3 the result is 18 instead of 12, and on 100 / 10 / 5 it is 50 instead of 2.
In a repeat code, count = int(ch) keeps only the last digit. On 10[a] the count becomes 0, no copy is added, and the output is a instead of ten letters. Build the count with count = count * 10 + digit.
In a path, only . and .. are special. A test such as part.startswith("..") also catches ..., which is an ordinary folder name. On /a/.../b it pops a and gives /b instead of /a/.../b.
. and empty parts. A name with dots is still a name.(. For many levels, use a stack of values and a stack of operators, and pop on the same or a higher precedence.Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Nesting
Q1/2 Why does a stack read nested brackets correctly?
Answer: B
Groups inside groups close from the inside out. The open groups, newest on top, are a stack, and every closing bracket ends the one on top.
Q2/2 A text uses only one kind of bracket, ( and ). You need to know how deeply nested each mark is. What is enough to keep?
Answer: B
Every open item is the same (, so only how many are open matters. The counter holds everything the stack would hold. With several kinds of bracket, you need the stack.
Checkpoint · Paths and repeat codes
Q1/3 What is the standard form of the path /a/./b/../../c?
Answer: C
The parts push a, then skip the ., then push b. The first .. pops b and the second pops a. Then c is pushed, so the path is /c.
Q2/3 In the path /a/.../b, what does the part ... do?
Answer: C
Only . and a part of exactly two dots are special. A part of three dots is an ordinary name, so the path stays /a/.../b.
Q3/3 What does the repeat code 2[a3[b]c] expand to?
Answer: C
The inner code 3[b] gives bbb. The group a + bbb + c is abbbc, and it is written twice: abbbcabbbc.
Checkpoint · Expressions
Q1/3 A calculator reads 6 + 4 * 3 - 8 / 5, with whole numbers and division that drops the fraction toward zero. What is its value?
Answer: B
The terms are 6, 12 and -8 / 5, which drops its fraction toward zero to give -1. The sum is 6 + 12 - 1 = 17.
Q2/3 A stack of terms holds -7, and the next part is / 2. In Python, -7 // 2 is -4. What must the calculator use, and why?
Answer: B
The exact value is -3.5, and dropping the fraction toward zero gives -3. Python's // rounds down to -4, so divide the size of the number and keep the sign.
Q3/3 A calculator evaluates 100 / 10 / 5. Which value is right, and why?
Answer: B
Divide is left to right: 100 / 10 = 10, and then 10 / 5 = 2. Working the right side first would give 50.
Checkpoint · Brackets
Q1/2 A calculator with brackets reads 10 - (2 + 3). What does it save when it reaches the (?
Answer: C
At (, the result so far and the sign in front of the bracket wait on a stack. At ), the group's value 5 is added with the saved sign, so the value is 10 - 5 = 5.
Q2/2 In which places is a - a sign (a unary minus), and not a subtraction?
Answer: C
After a number or a closing bracket, a - subtracts. At the start, or right after (, there is nothing to subtract from, so it is the sign of what follows, whether a number or a group.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.