|
3 | 3 | brackets are properly nested. A sequence of brackets s is considered properly nested |
4 | 4 | if any of the following conditions are true: |
5 | 5 |
|
6 | | - - s is empty |
7 | | - - s has the form (U) or [U] or {U} where U is a properly nested string |
8 | | - - s has the form VW where V and W are properly nested strings |
| 6 | + - s is empty |
| 7 | + - s has the form (U) or [U] or {U} where U is a properly nested string |
| 8 | + - s has the form VW where V and W are properly nested strings |
9 | 9 |
|
10 | 10 | For example, the string "()()[()]" is properly nested but "[(()]" is not. |
11 | 11 |
|
|
14 | 14 | """ |
15 | 15 |
|
16 | 16 |
|
17 | | -def is_balanced(s): |
18 | | - stack = [] |
19 | | - open_brackets = set({"(", "[", "{"}) |
20 | | - closed_brackets = set({")", "]", "}"}) |
| 17 | +def is_balanced(s: str) -> bool: |
| 18 | + """ |
| 19 | + >>> is_balanced("") |
| 20 | + True |
| 21 | + >>> is_balanced("()") |
| 22 | + True |
| 23 | + >>> is_balanced("[]") |
| 24 | + True |
| 25 | + >>> is_balanced("{}") |
| 26 | + True |
| 27 | + >>> is_balanced("()[]{}") |
| 28 | + True |
| 29 | + >>> is_balanced("(())") |
| 30 | + True |
| 31 | + >>> is_balanced("[[") |
| 32 | + False |
| 33 | + >>> is_balanced("([{}])") |
| 34 | + True |
| 35 | + >>> is_balanced("(()[)]") |
| 36 | + False |
| 37 | + >>> is_balanced("([)]") |
| 38 | + False |
| 39 | + >>> is_balanced("[[()]]") |
| 40 | + True |
| 41 | + >>> is_balanced("(()(()))") |
| 42 | + True |
| 43 | + >>> is_balanced("]") |
| 44 | + False |
| 45 | + >>> is_balanced("Life is a bowl of cherries.") |
| 46 | + True |
| 47 | + >>> is_balanced("Life is a bowl of che{}ies.") |
| 48 | + True |
| 49 | + >>> is_balanced("Life is a bowl of che}{ies.") |
| 50 | + False |
| 51 | + """ |
21 | 52 | open_to_closed = {"{": "}", "[": "]", "(": ")"} |
22 | | - |
23 | | - for i in range(len(s)): |
24 | | - if s[i] in open_brackets: |
25 | | - stack.append(s[i]) |
26 | | - |
27 | | - elif s[i] in closed_brackets and ( |
28 | | - len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != s[i]) |
| 53 | + stack = [] |
| 54 | + for symbol in s: |
| 55 | + if symbol in open_to_closed: |
| 56 | + stack.append(symbol) |
| 57 | + elif symbol in open_to_closed.values() and ( |
| 58 | + not stack or open_to_closed[stack.pop()] != symbol |
29 | 59 | ): |
30 | 60 | return False |
31 | | - |
32 | | - return len(stack) == 0 |
| 61 | + return not stack # stack should be empty |
33 | 62 |
|
34 | 63 |
|
35 | 64 | def main(): |
36 | 65 | s = input("Enter sequence of brackets: ") |
37 | | - if is_balanced(s): |
38 | | - print(s, "is balanced") |
39 | | - else: |
40 | | - print(s, "is not balanced") |
| 66 | + print(f"'{s}' is {'' if is_balanced(s) else 'not '}balanced.") |
41 | 67 |
|
42 | 68 |
|
43 | 69 | if __name__ == "__main__": |
| 70 | + from doctest import testmod |
| 71 | + |
| 72 | + testmod() |
44 | 73 | main() |
0 commit comments