|
| 1 | +""" |
| 2 | +Matching Brackets. |
| 3 | +
|
| 4 | +You're given the opportunity to write software for the Bracketeer™, |
| 5 | +an ancient but powerful mainframe. The software that runs on it is |
| 6 | +written in a proprietary language. Much of its syntax is familiar, |
| 7 | +but you notice lots of brackets, braces and parentheses. Despite |
| 8 | +the Bracketeer™ being powerful, it lacks flexibility. If the source |
| 9 | +code has any unbalanced brackets, braces or parentheses, the Bracketeer™ |
| 10 | +crashes and must be rebooted. To avoid such a scenario, you start writing |
| 11 | +code that can verify that brackets, braces, and parentheses are balanced |
| 12 | +before attempting to run it on the Bracketeer™. |
| 13 | +""" |
| 14 | + |
| 15 | +PAIRS: dict = { |
| 16 | + "]": "[", |
| 17 | + "}": "{", |
| 18 | + ")": "(", |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +def is_paired(input_string: str) -> bool: |
| 23 | + """ |
| 24 | + Verify that any and all pairs of brackets are matched. |
| 25 | +
|
| 26 | + Given a string containing brackets [], braces {}, parentheses (), |
| 27 | + or any combination thereof, verify that any and all pairs are matched |
| 28 | + and nested correctly. Any other characters should be ignored. For example, |
| 29 | + "{what is (42)}?" is balanced and "[text}" is not. |
| 30 | +
|
| 31 | + :param input_string: The string to check for balanced brackets |
| 32 | + :type input_string: str |
| 33 | + :returns: True if all brackets are properly paired and nested, False otherwise |
| 34 | + :rtype: bool |
| 35 | + """ |
| 36 | + # Empty string |
| 37 | + if not input_string: |
| 38 | + return True |
| 39 | + |
| 40 | + # Remove all non bracket items and convert a string to a list. |
| 41 | + brackets_list: list[str] = [ |
| 42 | + bracket for bracket in input_string if bracket in "(){}[]" |
| 43 | + ] |
| 44 | + |
| 45 | + # Odd number of brackets |
| 46 | + if len(brackets_list) % 2 != 0: |
| 47 | + return False |
| 48 | + |
| 49 | + stack: list[str] = [] |
| 50 | + for bracket in brackets_list: |
| 51 | + if bracket in "({[": |
| 52 | + stack.append(bracket) |
| 53 | + elif bracket in PAIRS: |
| 54 | + if not stack or stack.pop() != PAIRS[bracket]: |
| 55 | + return False |
| 56 | + |
| 57 | + return not stack |
0 commit comments