mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-24 05:21:09 +00:00
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>
This commit is contained in:
parent
a6831c898a
commit
a03b3f763f
|
@ -520,6 +520,7 @@
|
|||
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/other/sierpinski_triangle.py)
|
||||
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
|
||||
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/other/triplet_sum.py)
|
||||
* [Two Pointer](https://github.com/TheAlgorithms/Python/blob/master/other/two_pointer.py)
|
||||
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py)
|
||||
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/other/word_patterns.py)
|
||||
|
||||
|
|
|
@ -1,23 +1,37 @@
|
|||
from .stack import Stack
|
||||
|
||||
__author__ = "Omkar Pathak"
|
||||
|
||||
|
||||
def balanced_parentheses(parentheses):
|
||||
""" Use a stack to check if a string of parentheses is balanced."""
|
||||
stack = Stack(len(parentheses))
|
||||
for parenthesis in parentheses:
|
||||
if parenthesis == "(":
|
||||
stack.push(parenthesis)
|
||||
elif parenthesis == ")":
|
||||
if stack.is_empty():
|
||||
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
|
||||
stack.pop()
|
||||
return stack.is_empty()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from doctest import testmod
|
||||
|
||||
testmod()
|
||||
|
||||
examples = ["((()))", "((())", "(()))"]
|
||||
print("Balanced parentheses demonstration:\n")
|
||||
for example in examples:
|
||||
print(example + ": " + str(balanced_parentheses(example)))
|
||||
not_str = "" if balanced_parentheses(example) else "not "
|
||||
print(f"{example} is {not_str}balanced")
|
||||
|
|
Loading…
Reference in New Issue
Block a user