Advertisement
brainuser5705

Valid Parentheses

Dec 20th, 2020 (edited)
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.50 KB | None | 0 0
  1. def valid_parentheses(expression):
  2.     stack = []
  3.  
  4.     for symbol in expression:
  5.         if symbol in ['(', '[', '{']:
  6.             stack.append(symbol)
  7.  
  8.         # if the previous parentheses is a match, then pop that match
  9.         elif stack and (
  10.             (symbol == ')' and stack[-1] == '(') or\
  11.             (symbol == ']' and stack[-1] == '[') or\
  12.             (symbol == '}' and stack[-1] == '{')):
  13.             stack.pop()
  14.  
  15.     # the stack would be empty if all the parentheses match
  16.     return not stack
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement