Valid Parentheses Check
Check if parentheses are balanced.
AdvancedPhase 5 - Category 5: Advanced String LogicExample 13 of 14
valid-parentheses-check.py
1# Take string2s = input("Enter string with parentheses: ")34# Check balance5stack = []6valid = True7for char in s:8 if char in '([{':9 stack.append(char)10 elif char in ')]}':11 if not stack:12 valid = False13 break14 top = stack.pop()15 if (char == ')' and top != '(') or (char == ']' and top != '[') or (char == '}' and top != '{'):16 valid = False17 break1819if stack:20 valid = False2122print("Valid" if valid else "Invalid")
Output
Enter string with parentheses: ()[]{}
ValidWhat's going on
Use stack to match opening and closing.
Key Concepts:
Push opening brackets
Pop and match closing brackets
Check stack empty at end
🔗Related Content
- 📖
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- 📝
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- 💻
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum