Saturday, 22 January 2022

PythonSlip10b-Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' ']’. These brackets must be close in the correct order. for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid.

 Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' ']’. These brackets must be close in the correct order. for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid.      

class validity:

   def is_valid(self, str1):

        stack, pchar = [], {"(": ")", "{": "}", "[": "]"}

        for parenthese in str1:

            if parenthese in pchar:

                stack.append(parenthese)

            elif len(stack) == 0 or pchar[stack.pop()] != parenthese:

                return False

        return len(stack) == 0

 

print(validity().is_valid("(){}[]"))

print(validity().is_valid("()[{)}"))

print(validity().is_valid("()"))