| 35 | |
| 36 | |
| 37 | def isMatchingParens(strToCheck): |
| 38 | # A Python list is a stack data structure if we only push values on |
| 39 | # it with the append() method and pop values off it with the pop() |
| 40 | # method. The "top" of a Python list is the end of list. |
| 41 | stack = [] |
| 42 | |
| 43 | # Loop over every character in strToCheck. |
| 44 | for i, char in enumerate(strToCheck): |
| 45 | if char == '(': |
| 46 | stack.append('(') |
| 47 | print(strToCheck) |
| 48 | print((' ' * i) + '^ Push ( to the stack.') |
| 49 | print('STACK:', stack) |
| 50 | elif char == '{': |
| 51 | stack.append('{') |
| 52 | print(strToCheck) |
| 53 | print((' ' * i) + '^ Push { to the stack.') |
| 54 | print('STACK:', stack) |
| 55 | elif char == '[': |
| 56 | stack.append('[') |
| 57 | print(strToCheck) |
| 58 | print((' ' * i) + '^ Push [ to the stack.') |
| 59 | print('STACK:', stack) |
| 60 | elif char == ')' or char == '}' or char == ']': |
| 61 | if len(stack) == 0: |
| 62 | print(strToCheck) |
| 63 | print((' ' * i) + '^ Nothing to pop off the stack.') |
| 64 | print('STACK:', stack) |
| 65 | print('STACK IS ALREADY EMPTY.') |
| 66 | return False # Too many close parens/braces/brackets. |
| 67 | |
| 68 | if stack[-1] == '(': |
| 69 | expectedCloseChar = ')' |
| 70 | elif stack[-1] == '{': |
| 71 | expectedCloseChar = '}' |
| 72 | elif stack[-1] == '[': |
| 73 | expectedCloseChar = ']' |
| 74 | |
| 75 | if char == ')' and stack[-1] != '(': |
| 76 | print(strToCheck) |
| 77 | print((' ' * i) + '^ Pop ' + char + ' off the stack.') |
| 78 | print('STACK:', stack) |
| 79 | print('EXPECTED A ' + expectedCloseChar) |
| 80 | return False # Expected a close parenthesis. |
| 81 | elif char == '}' and stack[-1] != '{': |
| 82 | print(strToCheck) |
| 83 | print((' ' * i) + '^ Pop ' + char + ' off the stack.') |
| 84 | print('STACK:', stack) |
| 85 | print('EXPECTED A ' + expectedCloseChar) |
| 86 | return False # Expected a close brace. |
| 87 | elif char == ']' and stack[-1] != '[': |
| 88 | print(strToCheck) |
| 89 | print((' ' * i) + '^ Pop ' + char + ' off the stack.') |
| 90 | print('STACK:', stack) |
| 91 | print('EXPECTED A ' + expectedCloseChar) |
| 92 | return False # Expected a close bracket. |
| 93 | |
| 94 | # Remove the parens/braces/brackets from the stack's end: |