Last active
February 18, 2018 17:59
-
-
Save jion/b73b105cdefbdf888b1f72bcb146bb80 to your computer and use it in GitHub Desktop.
Exercise that I had to do in a live sharing-code interview
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(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