Skip to content

Instantly share code, notes, and snippets.

@citadelgrad
Last active November 9, 2019 15:37
Show Gist options
  • Save citadelgrad/3b22623c149d3b057e5592cbf9c76c08 to your computer and use it in GitHub Desktop.
Save citadelgrad/3b22623c149d3b057e5592cbf9c76c08 to your computer and use it in GitHub Desktop.
This is an example to efficiently push items onto a stack and remove them as you find matching pairs. https://www.youtube.com/watch?v=L3ud3rXpIxA&list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu&index=8
"""
Push items onto the Stack so that we can compare them as we process our string.
If the stack is not empty the element encapsulation is invalid.
"""
element = '[[{}]()]'
stack = list()
def matched_set(a, b):
return (a, b) in [('[',']'),('(',')'),('{','}')]
for character in element:
print("set: {}".format(stack))
if len(stack):
if matched_set(stack[-1], character):
stack.pop()
else:
stack.append(character)
else:
stack.append(character)
if stack:
print("This element is invalid")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment