Created
December 5, 2020 05:48
-
-
Save thetongs/b66bb4a8d5ed67eb11877bc8f672b2ae to your computer and use it in GitHub Desktop.
This file contains 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
## Balance parenthesis check | |
# | |
def checker(s): | |
# Check length | |
if(len(s) % 2 != 0): | |
return False | |
# set of opening brackets | |
opening = set('([{') | |
# set of matching pair | |
matches = set([ ('(',')'), ('[', ']'), ('{', '}')]) | |
# stack | |
stack = [] | |
# Check parenthesis | |
for paren in s: | |
if paren in opening: | |
stack.append(paren) | |
else: | |
if len(stack) == 0: | |
return False | |
last_open = stack.pop() | |
if(last_open, paren) not in matches: | |
return False | |
return len(stack) == 0 | |
# Feed | |
pa = '[]' | |
result = checker(pa) | |
print("{} - {}".format(pa, result)) | |
pa = '[][' | |
result = checker(pa) | |
print("{} - {}".format(pa, result)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment