Skip to content

Instantly share code, notes, and snippets.

@farhadmpr
Last active November 17, 2020 07:24
Show Gist options
  • Save farhadmpr/0b6bed0a490b0a0edebf226c89af4da9 to your computer and use it in GitHub Desktop.
Save farhadmpr/0b6bed0a490b0a0edebf226c89af4da9 to your computer and use it in GitHub Desktop.
Check for Balanced Brackets in an expression using Stack
# 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