Added doctests , type hints for other/nested_brackets.py (#10872)

* Added doctests , type hints

* Update nested_brackets.py

---------

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Bhavesh Mathur 2023-10-24 14:33:22 +05:30 committed by GitHub
parent 481aff7928
commit 17059b7ece
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,9 +3,9 @@ The nested brackets problem is a problem that determines if a sequence of
brackets are properly nested. A sequence of brackets s is considered properly nested brackets are properly nested. A sequence of brackets s is considered properly nested
if any of the following conditions are true: if any of the following conditions are true:
- s is empty - s is empty
- s has the form (U) or [U] or {U} where U is a properly nested string - s has the form (U) or [U] or {U} where U is a properly nested string
- s has the form VW where V and W are properly nested strings - s has the form VW where V and W are properly nested strings
For example, the string "()()[()]" is properly nested but "[(()]" is not. For example, the string "()()[()]" is properly nested but "[(()]" is not.
@ -14,31 +14,60 @@ brackets and returns true if S is nested and false otherwise.
""" """
def is_balanced(s): def is_balanced(s: str) -> bool:
stack = [] """
open_brackets = set({"(", "[", "{"}) >>> is_balanced("")
closed_brackets = set({")", "]", "}"}) True
>>> is_balanced("()")
True
>>> is_balanced("[]")
True
>>> is_balanced("{}")
True
>>> is_balanced("()[]{}")
True
>>> is_balanced("(())")
True
>>> is_balanced("[[")
False
>>> is_balanced("([{}])")
True
>>> is_balanced("(()[)]")
False
>>> is_balanced("([)]")
False
>>> is_balanced("[[()]]")
True
>>> is_balanced("(()(()))")
True
>>> is_balanced("]")
False
>>> is_balanced("Life is a bowl of cherries.")
True
>>> is_balanced("Life is a bowl of che{}ies.")
True
>>> is_balanced("Life is a bowl of che}{ies.")
False
"""
open_to_closed = {"{": "}", "[": "]", "(": ")"} open_to_closed = {"{": "}", "[": "]", "(": ")"}
stack = []
for i in range(len(s)): for symbol in s:
if s[i] in open_brackets: if symbol in open_to_closed:
stack.append(s[i]) stack.append(symbol)
elif symbol in open_to_closed.values() and (
elif s[i] in closed_brackets and ( not stack or open_to_closed[stack.pop()] != symbol
len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != s[i])
): ):
return False return False
return not stack # stack should be empty
return len(stack) == 0
def main(): def main():
s = input("Enter sequence of brackets: ") s = input("Enter sequence of brackets: ")
if is_balanced(s): print(f"'{s}' is {'' if is_balanced(s) else 'not '}balanced.")
print(s, "is balanced")
else:
print(s, "is not balanced")
if __name__ == "__main__": if __name__ == "__main__":
from doctest import testmod
testmod()
main() main()