Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Detecting balanced parentheses in Python
Parent
Detecting balanced parentheses in Python
The problem
Given a string s containing just the characters
'('
,')'
,'{'
,'}'
,'['
and']'
, determine if the input string is valid.An input string is valid if:
- Open brackets are closed by the same type of brackets.
- Open brackets are closed in the correct order.
The solution
def isValid(s: str) -> bool:
if len(s) % 2 != 0:
return False
for i in range(len(s) // 2):
s = s.replace("()", "").replace("[]", "").replace("{}", "")
return len(s) == 0
My approach to the problem is replacing the pairs. The string is balanced if the string is empty after replacing len(str) // 2
times. Is this a good approach? How can I improve my algorithm?
Use a stack while just scanning your string once from left to right. No need for multiple (performance-wise) expensive s …
3y ago
Instead of replacing the brackets, you could do just one loop, and keep a stack with the opening brackets. Every time yo …
3y ago
> Is this a good approach? How can I improve my algorithm? Your code is correct and simple. That is good, and it may …
10mo ago
Command-line timing Rather than using separate code for timing, I tried running the `timeit` module as a command-line …
10mo ago
You've got an inefficiency in your code, as you always do replacements 3/2 times the length of the string. That is unnec …
3y ago
Post
Use a stack while just scanning your string once from left to right. No need for multiple (performance-wise) expensive string replacements. If implemented right, the stack will only ever contain at maximum len(s)/2
elements.
The algorithm is rather straightforward:
Check first whether the string is of odd or even length. If the string is of odd length, it must be an unbalanced string (Your code already does this part, i just mentioned it here again simply for having a full description of the stack-based alogrithm.)
For any opening paranthesis/bracket/brace in the string, push some value/token that represents the type of this opening bracket onto the stack (that can be the opening bracket characters themselves, the associated closing brackets, or some other identifying values such as from an enum). If before doing a push the count of elements in the stack is already len(s)/2
you know the string must be unbalanced and the routine can abort now.
For any closing bracket in the string, pop a value/token from the stack and check whether that value/token represents the same bracket type as the closing bracket. If the stack is empty before attempting to pop, or the popped value/token mismatches the type of the closing bracket in the string, you know the string must be unbalanced and the routine can abort now.
When you finished scanning the string from left to right and the stack is not empty, you again know that the string must be unbalanced.
When the stack is empty after completing the scan of the text string, you know the string was balanced (or the string was empty).
I leave it to you as an exercise to translate this algorithm into concrete Python code.
P.S.: As a further exercise, you might try implementing the same stack-based algorithm while avoiding using an explicit stack data structure. This can be achieved by implementing the algorithm in a recursive manner, with the call stack conceptually taking the role of the stack that's keeping track of the (nested) bracket pairs.
0 comment threads