Last active
May 23, 2020 14:00
-
-
Save BHushanRathod/20d6e88d7deba7944a2c61abfe5c80b2 to your computer and use it in GitHub Desktop.
Python code to check the balanced paranthesis
This file contains hidden or 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
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok cool!