diff --git a/DIRECTORY.md b/DIRECTORY.md index 9e8981f5f61d57ec09bbe8ba7f75015d7c3d882c..ea5e01addeb01c61b2008d94ad9ea2edf38a95eb 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -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) diff --git a/data_structures/stacks/balanced_parentheses.py b/data_structures/stacks/balanced_parentheses.py index 7aacd59692779b82a887d758f5224ed4df2a1578..674f7ea436ed18f0ba50b9cb44adf603df01187d 100644 --- a/data_structures/stacks/balanced_parentheses.py +++ b/data_structures/stacks/balanced_parentheses.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")