|
| 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 | +LEFT: str = "[{(" |
| 16 | +RIGHT: str = "]})" |
| 17 | +PAIRS: dict = { |
| 18 | + "[": "]", |
| 19 | + "{": "}", |
| 20 | + "(": ")", |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +def is_paired(input_string: str) -> bool: |
| 25 | + """ |
| 26 | + Verify that any and all pairs of brackets are matched. |
| 27 | +
|
| 28 | + Given a string containing brackets [], braces {}, parentheses (), |
| 29 | + or any combination thereof, verify that any and all pairs are matched |
| 30 | + and nested correctly. Any other characters should be ignored. For example, |
| 31 | + "{what is (42)}?" is balanced and "[text}" is not. |
| 32 | +
|
| 33 | + :param input_string: |
| 34 | + :return: |
| 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 = [bracket for bracket in input_string if bracket in "(){}[]"] |
| 42 | + |
| 43 | + # Odd number of brackets |
| 44 | + if len(brackets_list) % 2 != 0: |
| 45 | + return False |
| 46 | + |
| 47 | + paired: bool = True |
| 48 | + while paired and brackets_list: |
| 49 | + for i, bracket in enumerate(brackets_list): |
| 50 | + # Right side bracket found |
| 51 | + if bracket in RIGHT: |
| 52 | + paired = False |
| 53 | + break |
| 54 | + |
| 55 | + # No matching pair found |
| 56 | + if ( |
| 57 | + brackets_list[i + 1] != PAIRS[bracket] |
| 58 | + and brackets_list[-1] != PAIRS[bracket] |
| 59 | + ): |
| 60 | + paired = False |
| 61 | + break |
| 62 | + |
| 63 | + # Matching pair found next to it |
| 64 | + if brackets_list[i + 1] == PAIRS[bracket]: |
| 65 | + del brackets_list[1] |
| 66 | + del brackets_list[0] |
| 67 | + break |
| 68 | + |
| 69 | + # Matching pair found at the end of the list |
| 70 | + if brackets_list[-1] == PAIRS[bracket]: |
| 71 | + del brackets_list[0] |
| 72 | + del brackets_list[-1] |
| 73 | + break |
| 74 | + |
| 75 | + return paired |
0 commit comments