- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathbalanced_parentheses.py
37 lines (31 loc) · 1.05 KB
/
balanced_parentheses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from .stackimportStack
defbalanced_parentheses(parentheses: str) ->bool:
"""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("")
True
"""
stack: Stack[str] =Stack()
bracket_pairs= {"(": ")", "[": "]", "{": "}"}
forbracketinparentheses:
ifbracketinbracket_pairs:
stack.push(bracket)
elifbracketin (")", "]", "}"):
ifstack.is_empty() orbracket_pairs[stack.pop()] !=bracket:
returnFalse
returnstack.is_empty()
if__name__=="__main__":
fromdoctestimporttestmod
testmod()
examples= ["((()))", "((())", "(()))"]
print("Balanced parentheses demonstration:\n")
forexampleinexamples:
not_str=""ifbalanced_parentheses(example) else"not "
print(f"{example} is {not_str}balanced")