()
| 4 | Tags: short, algorithm""" |
| 5 | __version__ = 0 |
| 6 | def main(): |
| 7 | print('''Matching Parentheses Algorithm |
| 8 | By Al Sweigart al@inventwithpython.com |
| 9 | |
| 10 | This demonstrates an algorithm for detecting matching parentheses, |
| 11 | curly braces, and square brackets in a string. For example: |
| 12 | |
| 13 | MATCHING NOT MATCHING |
| 14 | () )( |
| 15 | {}[] [[] |
| 16 | ({[]}) ({)} |
| 17 | {[][](())} {}} |
| 18 | |
| 19 | The algorithm works by using a "stack" data structure, where values |
| 20 | are only added or removed from the "top" of the stack. |
| 21 | |
| 22 | To check a string, we loop over each symbol in order. Opening |
| 23 | symbols are "pushed" (added) to the stack, while closing symbols |
| 24 | "pop" (remove) the symbol off of the stack (but only if it's matches |
| 25 | the opening symbol at the top of the stack.) |
| 26 | The string has matching parentheses/braces/brackets if the stack is |
| 27 | empty at the end of the string. |
| 28 | ''') |
| 29 | print('Enter the string to check, for example {[][](())}:') |
| 30 | response = input('> ') |
| 31 | print() |
| 32 | |
| 33 | result = isMatchingParens(response) |
| 34 | print('"' + response + '"', 'IS MATCHING:', result) |
| 35 | |
| 36 | |
| 37 | def isMatchingParens(strToCheck): |
no test coverage detected