๐ What I Learned Today: Mastering Stacks and Balanced Parentheses in Python ๐

๐ง Date: Todayโs session was all about stacks and practical problem solving.
๐ A Quick Recap of My Progress
Today, I dove into the world of stacks โ a powerful linear data structure that follows the Last In, First Out (LIFO) principle. I learned how to use basic stack operations like:
push()
โ Add an element to the top of the stackpop()
โ Remove the element from the top of the stackpeek()
(often calledtop
orstack[-1]
) โ Look at the top element without removing it
๐งฉ Real-World Problem: Validating Balanced Parentheses
To solidify my understanding of stacks, I tackled a classic coding challenge: checking whether a string of parentheses is balanced. This means that every opening bracket like (
, {
, or [
must have a corresponding and correctly ordered closing bracket: )
, }
, or ]
.
๐ The Problem-Solving Steps I Followed:
1. Traverse the string character by character.
2. If you encounter an opening parenthesis, push it to the stack.
3. If you encounter a closing parenthesis, check if there is a corresponding opening parenthesis at the top of the stack.
- If there is, pop it from the stack.
- If not, the string is unbalanced.
4. After traversing the whole string, if the stack is empty, the parentheses are balanced.
๐งช Hereโs the Python Code I Wrote
#solving problems using stack
chars = "(())(()){}}"
stack = []
# mapping of closing to opening
pairs = {
')': '(',
'}': '{',
']': '['
}
for char in chars:
if char in '({[':
stack.append(char)
elif char in ')}]':
if not stack:
print("Unbalanced: No matching opening for", char)
break
elif stack[-1] == pairs[char]:
stack.pop()
else:
print("Unbalanced: Expected", pairs[char], "but found", stack[-1])
break
else:
if not stack:
print("โ
All parentheses are balanced!")
else:
print("โ Unbalanced: Some opening parentheses were not closed:", stack)
๐ง What I Learned:
Stacks are incredibly useful for problems involving nested structure or reversing order.
The
stack.pop()
method is great for backtracking to the most recent opening parenthesis.The Python
else
block on afor
loop was new to me! It only runs when the loop completes without abreak
.
Subscribe to my newsletter
Read articles from kasumbi phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
