Last active
November 17, 2020 07:24
-
-
Save farhadmpr/0b6bed0a490b0a0edebf226c89af4da9 to your computer and use it in GitHub Desktop.
Check for Balanced Brackets in an expression using Stack
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
# Python3 program to check for | |
# balanced brackets. | |
# function to check if | |
# brackets are balanced | |
def areBracketsBalanced(expr): | |
stack = [] | |
# Traversing the Expression | |
for char in expr: | |
if char in ["(", "{", "["]: | |
# Push the element in the stack | |
stack.append(char) | |
else: | |
# IF current character is not opening | |
# bracket, then it must be closing. | |
# So stack cannot be empty at this point. | |
if not stack: | |
return False | |
current_char = stack.pop() | |
if current_char == '(': | |
if char != ")": | |
return False | |
if current_char == '{': | |
if char != "}": | |
return False | |
if current_char == '[': | |
if char != "]": | |
return False | |
# Check Empty Stack | |
if stack: | |
return False | |
return True | |
# Driver Code | |
if __name__ == "__main__": | |
expr = "{()}[]" | |
# Function call | |
if areBracketsBalanced(expr): | |
print("Balanced") | |
else: | |
print("Not Balanced") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment