Skip to content

Instantly share code, notes, and snippets.

@BHushanRathod
Last active May 23, 2020 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BHushanRathod/20d6e88d7deba7944a2c61abfe5c80b2 to your computer and use it in GitHub Desktop.
Save BHushanRathod/20d6e88d7deba7944a2c61abfe5c80b2 to your computer and use it in GitHub Desktop.
Python code to check the balanced paranthesis
def check_paranthesis(expression):
para_list = []
is_paranthesis = True
paradict = dict()
paradict.update({')': '(', '}': '{', ']': '['})
opening = ['(', '{', '[']
closing = [')', '}', ']']
for n in expression:
if n in opening:
para_list.append(n)
print("---------------")
print("Added: ", n)
print("List: ", para_list)
if n in closing:
if len(para_list) > 0:
if para_list[-1] == paradict.get(n):
para_list.pop()
print("---------------")
print("Removed: ", n)
print("List: ", para_list)
else:
is_paranthesis = False
print("List is empty")
return is_paranthesis, para_list
# Example:
# A = "(a+b)+{a+b*(abc)}"
# A = "(a+b*[bc * ab + (a+b)])+{a+b*(abc)}"
# A = "(a+b)+{a+b*(abc)}))"
# A = "[]{[}"
result, list = check_paranthesis(A)
print("---------Result------------")
if result and not list:
print("Balanced Paranthesis")
else:
print("Paranthesis Missing")
@themrinalsinha
Copy link

Ok cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment