Created
May 18, 2018 12:01
-
-
Save gabraganca/8c550c36149e30c01d5bc2879e17e57c to your computer and use it in GitHub Desktop.
Check if multiple brackets 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(s): | |
""" | |
Check if a string has balanced brackets. | |
Parameters | |
---------- | |
s: str | |
String to be checked. | |
Returns | |
------- | |
True if the rbackets are balanced. False otherwise | |
""" | |
if len(s) == 1: | |
# Only one char. It can't be balanced | |
return False | |
else: | |
# Add counters | |
count_dic = {'[':0, | |
'(':0, | |
'{':0} | |
# Bracket reference | |
ref_dic = {']':'[', | |
')':'(', | |
'}':'{'} | |
# Store the opening brackets checked | |
bracket_list = [] | |
for char in s: | |
if char in count_dic.keys(): | |
count_dic[char] += 1 | |
bracket_list.append(char) | |
elif char in ref_dic.keys(): | |
# Decerease count | |
count_dic[ref_dic[char]] -= 1 | |
# Check if it matches the last one | |
if ref_dic[char] == bracket_list[-1]: | |
_ = bracket_list.pop() | |
else: | |
return False | |
# Check if any counter is negative | |
for count in count_dic.values(): | |
if count < 0: | |
return False | |
return True | |
assert is_balanced("[()]{a}{[(())]()}") | |
assert not is_balanced("[(])") | |
assert not is_balanced("(((]]]") | |
assert not is_balanced(')') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment