Created
June 24, 2018 00:59
-
-
Save accessnash/97227bc931b5eaab55e02c0c11c0aff4 to your computer and use it in GitHub Desktop.
Balanced brackets problem from Hackerrank
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 balanced( a_str): | |
| if len(a_str) %2 !=0: | |
| return False | |
| open_bracks = ['(', '{', '['] | |
| close_bracks = [')', '}', ']'] | |
| par_dict = {open_bracks[0]:close_bracks[0], open_bracks[1]:close_bracks[1], open_bracks[2]:close_bracks[2]} | |
| if a_str[0] in close_bracks: | |
| return False | |
| if a_str[-1] in open_bracks: | |
| return False | |
| match = [] | |
| for i in a_str: | |
| if i in open_bracks: | |
| match.append(par_dict[i]) | |
| elif i in close_bracks: | |
| if not match or i != match.pop(): | |
| return False | |
| return not match |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment