Created
April 25, 2022 16:13
-
-
Save tiagocoutinho/97890b9133eab2e36f973ce131288d4f to your computer and use it in GitHub Desktop.
Balanced parenthesis in python
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
opening = "([{" | |
closing = ")]}" | |
def balanced(expr): | |
stack = [] | |
for c in expr: | |
if c in opening: | |
stack.append(c) | |
elif c in closing: | |
idx = closing.index(c) | |
if stack and stack[-1] == opening[idx]: | |
stack.pop() | |
else: | |
return False | |
return not stack |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment