Created
May 25, 2020 16:48
-
-
Save theoctober19th/f4df02df4a4a8795b4c29c0c78802cf0 to your computer and use it in GitHub Desktop.
Python function that checks if the brackets in a given string are balanced:
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 is_balanced(string): | |
stack = [] | |
for ch in string: | |
if ch in ['(', '{', '[']: | |
stack.append(ch) | |
else: | |
if ch == ')' and stack and stack[-1] == '(': | |
stack.pop() | |
if ch == '}' and stack and stack[-1] == '{': | |
stack.pop() | |
if ch == ']'and stack and stack[-1] == '[': | |
stack.pop() | |
return False if stack else True | |
sample = '{}{}((()(())[]))()' | |
print(is_balanced(sample)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment