MCPcopy
hub / github.com/TheAlgorithms/Python / balanced_parentheses

Function balanced_parentheses

data_structures/stacks/balanced_parentheses.py:4–26  ·  view source on GitHub ↗

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("")

(parentheses: str)

Source from the content-addressed store, hash-verified

2
3
4def 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[str] = Stack()
18 bracket_pairs = {"(": ")", "[": "]", "{": "}"}
19 for bracket in parentheses:
20 if bracket in bracket_pairs:
21 stack.push(bracket)
22 elif bracket in (")", "]", "}") and (
23 stack.is_empty() or bracket_pairs[stack.pop()] != bracket
24 ):
25 return False
26 return stack.is_empty()
27
28
29if __name__ == "__main__":

Callers 2

infix_to_postfixFunction · 0.90

Calls 4

pushMethod · 0.95
is_emptyMethod · 0.95
popMethod · 0.95
StackClass · 0.70

Tested by

no test coverage detected