Skip to content

Instantly share code, notes, and snippets.

@Abhayparashar31
Created September 30, 2020 04:16
Show Gist options
  • Save Abhayparashar31/8b8274dc448346da8dceb882d71a222a to your computer and use it in GitHub Desktop.
Save Abhayparashar31/8b8274dc448346da8dceb882d71a222a to your computer and use it in GitHub Desktop.
class Stack():
def __init__(self):
self.items = [] ## Empty list intilize
def push(self,item):
self.items.append(item) ## simple appending to list
def pop(self):
return self.items.pop() ## Removing top element of the stack
def is_empty(self):
return self.items==[] ### Checking whether the stack is empty or not
def peek(self):
if not self.is_empty():
return self.items[-1] ## returnign top element using [-1]=last element
def show_stack(self):
return self.items ## Printing all the items
def is_match(p1,p2):
if p1 == '(' and p2 == ')':
return True
if p1 == '[' and p2 == ']':
return True
if p1 == '{' and p2 == '}':
return True
else :
return False
def check_paren_balanced(paren_string):
s = Stack()
is_balance = True
index = 0
while index < len(paren_string) and is_balance:
paren = paren_string[index]
if paren in '({[':
s.push(paren)
else :
if s.is_empty():
is_balance = False
else :
top = s.pop()
if not is_match(top,paren):
is_balance = False
index +=1
if s.is_empty and is_balance :
return True
else :
return False
string = str(input("Enter the set of parenthesis :\n"))
print(check_paren_balanced(string))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment