Skip to content

Instantly share code, notes, and snippets.

@jfrobbins
Created February 27, 2014 16:37
Show Gist options
  • Select an option

  • Save jfrobbins/9253743 to your computer and use it in GitHub Desktop.

Select an option

Save jfrobbins/9253743 to your computer and use it in GitHub Desktop.
"""
balancedparentheses.py
Program to check for balanced parentheses in an expression using stack
To run you only need Python3 installed
To exectue:
python3 balancedparentheses.py
modified from the code here: http://www.lifengadget.com/lifengadget/program-to-check-for-balanced-parentheses-in-an-expression/
"""
def bracketsame(opening,closing): # function checks if opening and closing brackets are same
if(opening == '(' and closing == ')') :
return True
elif(opening == '{' and closing == '}'):
return True
elif(opening == '[' and closing == ']') :
return True
return False
def balancedparantheses(exp): #checks if parentheses are balanced or not
stack = []
for c in exp:
if(c == '(' or c == '{' or c == '['):
stack.append(c)
elif(c == ')' or c == '}' or c == ']'):
if(len(stack) == 0 or not bracketsame(stack[-1],c)):
return False
else:
stack.pop(len(stack)-1)
if len(stack) == 0:
return True
else:
return False
# =========================================================
# main
getOut = False
while getOut == False:
expression = input("Enter an expression to check: ")
if(balancedparantheses(expression)):
print("Balanced expression \n")
else:
print("Expression is not balanced \n")
userEntered = input("press q to exit, any key to continue:")
if userEntered.lower() == 'q':
getOut = True
print('user exiting')
else:
getOut = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment