Skip to content

Instantly share code, notes, and snippets.

@QuantumFractal
Created August 22, 2015 02:20
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 QuantumFractal/8e658af4989e8a8d780a to your computer and use it in GitHub Desktop.
Save QuantumFractal/8e658af4989e8a8d780a to your computer and use it in GitHub Desktop.
Python snippet
def check_parenthesis(string):
stack = Stack()
# We're using a dict which allows us to do some fun things!
brackets = {'{':'}', '[':']', '(':')'}
for character in string:
# Keys being the left-side brackets
if character in brackets.keys():
stack.push(character)
# Values being the right-side brackets
if character in brackets.values():
try:
other = stack.pop()
# Check for it's pair using the dict earlier
if brackets[other] != character:
return False
except ValueError:
return False
# If we've made it all the way through without incident
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment