Python/data_structures/stacks/balanced_parentheses.py
Du Yuanchao a03b3f763f
Balanced parentheses (#3768)
* Fixed balanced_parentheses.py

* fixed pre-commit

* eliminate is_paired

* remove unused line

* updating DIRECTORY.md

* Update data_structures/stacks/balanced_parentheses.py

Co-authored-by: Christian Clauss <cclauss@me.com>

* Add more test cases

* Update data_structures/stacks/balanced_parentheses.py

Co-authored-by: Christian Clauss <cclauss@me.com>

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
2020-10-29 10:39:19 +01:00

38 lines
1.0 KiB
Python

from .stack import Stack
def balanced_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()
bracket_pairs = {"(": ")", "[": "]", "{": "}"}
for bracket in parentheses:
if bracket in bracket_pairs:
stack.push(bracket)
elif bracket in (")", "]", "}"):
if stack.is_empty() or bracket_pairs[stack.pop()] != bracket:
return False
return stack.is_empty()
if __name__ == "__main__":
from doctest import testmod
testmod()
examples = ["((()))", "((())", "(()))"]
print("Balanced parentheses demonstration:\n")
for example in examples:
not_str = "" if balanced_parentheses(example) else "not "
print(f"{example} is {not_str}balanced")