MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / is_balanced

Function is_balanced

other/nested_brackets.py:17–61  ·  view source on GitHub ↗

>>> is_balanced("") True >>> is_balanced("()") True >>> is_balanced("[]") True >>> is_balanced("{}") True >>> is_balanced("()[]{}") True >>> is_balanced("(())") True >>> is_balanced("[[") False >>> is_balanced("([{}])") True >>> is

(s: str)

Source from the content-addressed store, hash-verified

15
16
17def 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 """
52 open_to_closed = {"{": "}", "[": "]", "(": ")"}
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
59 ):
60 return False
61 return not stack # stack should be empty
62
63
64def main():

Callers 1

mainFunction · 0.85

Calls 2

appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected