write a python code that detects if the paranthesis in a string are matching
- User
write a python code that detects if the paranthesis in a string are matching
- Assistant
Here is a Python code that detects if the parentheses in a string are matching:
def matching_parentheses(s): stack = [] for char in s: if char == '(': stack.append(char) elif char == ')': if len(stack) == 0: return False stack.pop() if len(stack) == 0: return True else: return False # Test the function s1 = "((()))" s2 = "(()))(" s3 = "())(" print(matching_parentheses(s1)) # Output: True print(matching_parentheses(s2)) # Output: False print(matching_parentheses(s3)) # Output: FalseThis code uses a stack to keep track of opening parentheses encountered in the string. When a closing parentheses is encountered, it is removed from the stack. If at the end of the string, the stack is empty, then the parentheses are matching.
- User
can you use libraries
- Assistant
Yes, you can also use the
re(regular expression) library in Python to check if the parentheses in a string are matching. Here is an example code using therelibrary:import re def matching_parentheses(s): pattern = r"\([^()]*\)" while re.search(pattern, s): s = re.sub(pattern, "", s) return not bool(re.search(r"[()]", s)) # Test the function s1 = "((()))" s2 = "(()))(" s3 = "())(" print(matching_parentheses(s1)) # Output: True print(matching_parentheses(s2)) # Output: False print(matching_parentheses(s3)) # Output: FalseThis code uses regular expressions to replace any matching pairs of parentheses with an empty string until there are no more pairs left in the string. Finally, it checks if there are any remaining parentheses in the modified string to determine if the parentheses are matching.