Check for balanced parentheses in Python
Given an expression string, write a python program to find whether a given string has balanced parentheses or not.
Examples:
Input : {[]{()}}
Output : Balanced
Input : [{}{}(]
Output : Unbalanced
Approach #1 : Using stack
One approach to check balanced parentheses is to use stack. Each time, when an open parentheses is encountered push it in the stack, and when closed parenthesis is encountered, match it with the top of stack and pop it. If stack is empty at the end, return Balanced otherwise, Unbalanced.
# Python3 code to Check for # balanced parentheses in an expression open_list = ["[","{","("] close_list = ["]","}",")"] # Function to check parentheses def check(myStr): stack = [] for i in myStr: if i in open_list: stack.append(i) elif i in close_list: pos = close_list.index(i) if ((len(stack) > 0) and (open_list[pos] == stack[len(stack)-1])): stack.pop() else: return "Unbalanced" if len(stack) == 0: return "Balanced" # Driver code string = "{[]{()}}"print(string,"-", check(string)) string = "[{}{})(]"print(string,"-", check(string)) |
{[]{()}} - Balanced
[{}{})(] - Unbalanced
Approach #2 : Using queue
First Map opening parentheses to respective closing parentheses. Iterate through the given expression using ‘i’, if ‘i’ is an open parentheses, append in queue, if ‘i’ is close parentheses, Check whether queue is empty or ‘i’ is the top element of queue, if yes, return “Unbalanced”, otherwise “Balanced”.
# Python3 code to Check for # balanced parentheses in an expression def check(expression): open_tup = tuple('({[') close_tup = tuple(')}]') map = dict(zip(open_tup, close_tup)) queue = [] for i in expression: if i in open_tup: queue.append(map[i]) elif i in close_tup: if not queue or i != queue.pop(): return "Unbalanced" return "Balanced" # Driver code string = "{[]{()}}"print(string, "-", check(string)) |
{[]{()}} - Balanced
Approach#3 : Elimination based
In every iteration, the innermost brackets get eliminated (replaced with empty string). If we end up with an empty string, our initial one was balanced; otherwise, not.
# Python3 code to Check for # balanced parentheses in an expression def check(my_string): brackets = ['()', '{}', '[]'] while any(x in my_string for x in brackets): for br in brackets: my_string = my_string.replace(br, '') return not my_string # Driver code string = "{[]{()}}"print(string, "-", "Balanced" if check(string) else "Unbalanced") |
{[]{()}} - Balanced
Recommended Posts:
- Check for balanced parentheses in an expression
- Check for balanced parentheses in an expression | O(1) space
- Print all combinations of balanced parentheses
- Pairs involved in Balanced Parentheses
- Length of longest balanced parentheses prefix
- Count pairs of parentheses sequences such that parantheses are balanced
- Remove Invalid Parentheses
- Find the number of valid parentheses expressions of given length
- Minimum number of Parentheses to be added to make it valid
- Python | Check for URL in a String
- Python | Check whether given key already exists in a dictionary
- Python | Check if one list is subset of other
- Python | Check if list is sorted or not
- Python set to check if string is panagram
- Python | Check if a given object is list or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



