Skip to content

Commit 17059b7

Browse files
bhavesh1oocclauss
andauthored
Added doctests , type hints for other/nested_brackets.py (#10872)
* Added doctests , type hints * Update nested_brackets.py --------- Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 481aff7 commit 17059b7

File tree

1 file changed

+49
-20
lines changed

1 file changed

+49
-20
lines changed

other/nested_brackets.py

+49-20
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
brackets are properly nested. A sequence of brackets s is considered properly nested
44
if any of the following conditions are true:
55
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
99
1010
For example, the string "()()[()]" is properly nested but "[(()]" is not.
1111
@@ -14,31 +14,60 @@
1414
"""
1515

1616

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+
"""
2152
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
2959
):
3060
return False
31-
32-
return len(stack) == 0
61+
return not stack # stack should be empty
3362

3463

3564
def main():
3665
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.")
4167

4268

4369
if __name__ == "__main__":
70+
from doctest import testmod
71+
72+
testmod()
4473
main()

0 commit comments

Comments
 (0)