Skip to content

Instantly share code, notes, and snippets.

@jion
Last active February 18, 2018 17:59
Show Gist options
  • Save jion/b73b105cdefbdf888b1f72bcb146bb80 to your computer and use it in GitHub Desktop.
Save jion/b73b105cdefbdf888b1f72bcb146bb80 to your computer and use it in GitHub Desktop.
Exercise that I had to do in a live sharing-code interview
def is_balanced(input_string):
pending_braces = list()
open_braces, closing_braces = '[{(', ']})'
for c in input_string:
if c in open_braces:
index = open_braces.index(c)
pending_braces.append(closing_braces[index])
continue
if c in closing_braces:
last_brace = pending_braces.pop() if pending_braces else None
if c != last_brace:
return False
return not pending_braces
# Test cases:
print is_balanced('[()]{}{[(())]()}')
print is_balanced('[(])')
print is_balanced(')[(])')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment