Skip to content

Instantly share code, notes, and snippets.

@DagnyTagg2013
Created November 6, 2017 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DagnyTagg2013/a3fd08633ff359f745b5f82d6880185a to your computer and use it in GitHub Desktop.
Save DagnyTagg2013/a3fd08633ff359f745b5f82d6880185a to your computer and use it in GitHub Desktop.
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