|
1 | 1 | from .stack import Stack
|
2 | 2 |
|
3 |
| -__author__ = "Omkar Pathak" |
4 | 3 |
|
5 |
| - |
6 |
| -def balanced_parentheses(parentheses): |
7 |
| - """ Use a stack to check if a string of parentheses is balanced.""" |
8 |
| - stack = Stack(len(parentheses)) |
9 |
| - for parenthesis in parentheses: |
10 |
| - if parenthesis == "(": |
11 |
| - stack.push(parenthesis) |
12 |
| - elif parenthesis == ")": |
13 |
| - if stack.is_empty(): |
| 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() |
| 18 | + bracket_pairs = {"(": ")", "[": "]", "{": "}"} |
| 19 | + for bracket in parentheses: |
| 20 | + if bracket in bracket_pairs: |
| 21 | + stack.push(bracket) |
| 22 | + elif bracket in (")", "]", "}"): |
| 23 | + if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: |
14 | 24 | return False
|
15 |
| - stack.pop() |
16 | 25 | return stack.is_empty()
|
17 | 26 |
|
18 | 27 |
|
19 | 28 | if __name__ == "__main__":
|
| 29 | + from doctest import testmod |
| 30 | + |
| 31 | + testmod() |
| 32 | + |
20 | 33 | examples = ["((()))", "((())", "(()))"]
|
21 | 34 | print("Balanced parentheses demonstration:\n")
|
22 | 35 | for example in examples:
|
23 |
| - print(example + ": " + str(balanced_parentheses(example))) |
| 36 | + not_str = "" if balanced_parentheses(example) else "not " |
| 37 | + print(f"{example} is {not_str}balanced") |
0 commit comments