Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
detectValidExpressionBracketsMatch
"""
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
You can’t perform that action at this time.