Skip to content

Instantly share code, notes, and snippets.

@theoctober19th
Created May 25, 2020 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theoctober19th/f4df02df4a4a8795b4c29c0c78802cf0 to your computer and use it in GitHub Desktop.
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:
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