Last active
November 18, 2021 00:16
-
-
Save muhammad-mobeen/8836c28838755a4d8c3b1cbaa3ef60d0 to your computer and use it in GitHub Desktop.
Python Program to check for balanced parentheses in an expression using stack class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Python Program to check for balanced parentheses in an expression using stack class. | |
Given an expression as string comprising of opening and closing characters | |
of parentheses - (), curly braces - {} and square brackets - [], we need to | |
check whether symbols are balanced or not. | |
''' | |
from collections import deque # importing "double-ended queue" | |
class Stack: # class for making a stack | |
def __init__(self): # constructor | |
self.control = deque() # initializing class object as a deque | |
def push(self, value): # function for appending stack | |
self.control.append(value) | |
def pop(self): # function to pop out latest value | |
return self.control.pop() | |
def size(self): # returns the size of stack | |
return len(self.control) | |
def is_empty(self): # returns if stack is empty or not | |
return len(self.control) == 0 | |
def show(self): # pops whole stack and prints it | |
for x in range(len(self.control)): | |
print("'", end="") | |
print(self.control.pop(), end="") | |
print("'", end=",") | |
def parentheses_check(exp): # function for balancing parentheses | |
stack = Stack() | |
brackets = {'(': ')', '[': ']', '{': '}'} # dict for storing brackets | |
for i in exp: # loop to iterate over string | |
if i in brackets.keys(): # check if it's opening bracket | |
stack.push(i) # append to stack | |
elif i in brackets.values(): # check if it's closing bracket | |
popped = "" | |
if not stack.is_empty(): | |
popped = stack.pop() | |
""" | |
Below if condition checks following conditions:- | |
(if encountered closing bracket first) or (if it is not the pair of popped bracket) | |
""" | |
if (stack.is_empty() and popped == "") or (i != brackets.get(popped)): | |
print("Not Balanced!\nError: No opening brackets was found for: ", end="") | |
print("'", end="") | |
print(i, end="") | |
print("'") | |
return | |
if stack.is_empty(): # nothing in stack means all is well/balanced ;) | |
print("All Balanced! You are good to go.") | |
else: | |
print("Not Balanced!\nError: No closing brackets were found for: ", end="") | |
stack.show() | |
parentheses_check("{[(a+b)*c]/d}") # parsing a string value (expression) for balance check |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment