Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("")
(parentheses: str)
| 2 | |
| 3 | |
| 4 | def balanced_parentheses(parentheses: str) -> bool: |
| 5 | """Use a stack to check if a string of parentheses is balanced. |
| 6 | >>> balanced_parentheses("([]{})") |
| 7 | True |
| 8 | >>> balanced_parentheses("[()]{}{[()()]()}") |
| 9 | True |
| 10 | >>> balanced_parentheses("[(])") |
| 11 | False |
| 12 | >>> balanced_parentheses("1+2*3-4") |
| 13 | True |
| 14 | >>> balanced_parentheses("") |
| 15 | True |
| 16 | """ |
| 17 | stack: Stack[str] = Stack() |
| 18 | bracket_pairs = {"(": ")", "[": "]", "{": "}"} |
| 19 | for bracket in parentheses: |
| 20 | if bracket in bracket_pairs: |
| 21 | stack.push(bracket) |
| 22 | elif bracket in (")", "]", "}") and ( |
| 23 | stack.is_empty() or bracket_pairs[stack.pop()] != bracket |
| 24 | ): |
| 25 | return False |
| 26 | return stack.is_empty() |
| 27 | |
| 28 | |
| 29 | if __name__ == "__main__": |
no test coverage detected