Created
November 6, 2017 06:48
-
-
Save DagnyTagg2013/a3fd08633ff359f745b5f82d6880185a to your computer and use it in GitHub Desktop.
detectValidExpressionBracketsMatch
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
""" | |
MATCH BRACKETS | |
""" | |
""" | |
BAM: dynamic STACK - append opens, then match-pop on closes | |
DICT to match CLOSE to OPEN (as BACK-MATCH), | |
used as SET to filter non-parens | |
SET to filter opens and ignore non-parens | |
ROBUST: isValid = False by DEFAULT, break out | |
ATTN: pop() correction to simulate peek() | |
don't care about non-brackets! | |
""" | |
def checkMatch(expr): | |
# default | |
isValid = False | |
close_matches = { | |
')':'(', | |
'}':'{', | |
']':'[' | |
} | |
opens = { '(', '{', '[' } | |
stack = [] | |
# - load LIFO Stack open | |
# - skip non-parens; as don't care | |
# - POP on closes as match on-the-fly | |
# - MOVEON! | |
# skip chars or non-brackets as don't care | |
for aChar in expr: | |
# IGNORE chars, or non-brackets | |
if aChar in opens: | |
stack.append(aChar) | |
elif aChar in close_matches: | |
# simulate peek | |
peekTop = stack.pop() | |
# print(peekTop) | |
if (peekTop == close_matches[aChar]): | |
# good match, prior pop good for match! | |
isValid = True | |
pass | |
else: | |
# NO match, FALSE expression, break out! | |
# print("BREAK!") | |
break | |
else: | |
# don't care | |
pass | |
print(stack) | |
# if you have unmatched brackets leftover | |
if not stack: | |
return isValid | |
else: | |
return isValid | |
# TRUE | |
# isMatch = checkMatch("") | |
# TRUE | |
# isMatch = checkMatch("ab") | |
# TRUE | |
# isMatch = checkMatch("({})") | |
# FALSE | |
# isMatch = checkMatch("(a{bc}") | |
# FALSE - FUCK! | |
isMatch = checkMatch("{)") | |
print(isMatch) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment