Sub topic 8
Stack Applications: Balanced Parentheses, Infix to Postfix, and Postfix Evaluation
Assume you know loops, functions, lists, and Big-O notation. A stack is an abstract data type that follows LIFO, or “last in, first out.” The last item pushed is the first item popped. Its main operations are push, pop, and peek.
Balanced Parentheses
A bracket is matched when every closing bracket has the same type as the most recent unmatched opening bracket. A stack stores opening brackets. When a closing bracket appears, it must match the stack’s top item.
def is_balanced(text):
opening = "([{"
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in text:
if ch in opening:
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(is_balanced("{[()]}")) # True
print(is_balanced("{[(])}")) # FalseThe algorithm takes O(n) time because it examines each character once. The stack uses O(n) space in the worst case.
Infix to Postfix
Infix notation places operators between operands, such as 2 + 3 * 4. Postfix notation, also called reverse Polish notation, places each operator after its operands: 2 3 4 * +.
The output list receives operands immediately. Operators wait in a stack until precedence allows them to be output. Parentheses control when operators are popped.
def infix_to_postfix(tokens):
precedence = {"+": 1, "-": 1, "*": 2, "/": 2}
output = []
operators = []
for token in tokens:
if token.isdigit():
output.append(token)
elif token == "(":
operators.append(token)
elif token == ")":
while operators[-1] != "(":
output.append(operators.pop())
operators.pop()
else:
while (operators and operators[-1] != "(" and
precedence[operators[-1]] >= precedence[token]):
output.append(operators.pop())
operators.append(token)
while operators:
output.append(operators.pop())
return output
def evaluate_postfix(tokens):
stack = []
for token in tokens:
if token.isdigit():
stack.append(int(token))
else:
right = stack.pop()
left = stack.pop()
if token == "+":
stack.append(left + right)
elif token == "-":
stack.append(left - right)
elif token == "*":
stack.append(left * right)
else:
stack.append(left // right)
return stack.pop()
postfix = infix_to_postfix("2 + 3 * 4".split())
print(postfix) # ['2', '3', '4', '*', '+']
print(evaluate_postfix(postfix)) # 14During postfix evaluation, the first popped value is the right operand. Reversing these operands causes subtraction and division errors.
| Task | Stack action | Cost |
|---|---|---|
| Balanced brackets | Push openers, pop matches | O(n) |
| Infix to postfix | Hold pending operators | O(n) |
| Postfix evaluation | Pop two operands, push result | O(n) |
Exercise
Convert 8 / 2 + 3 to postfix and evaluate it.
Show answer
Postfix is 8 2 / 3 +; its value is 7.