I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.
I have seen examples here using the stack command which I haven't encountered yet. So I attempted a different approach. Can anyone tell me where I am going wrong?
def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
else:
if l == ")":
clo = clo + [")"]
else:
return(ope, clo)
if len(ope)==len(clo):
return True
else:
return False
The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant I which held either ( or ) respectively.
Push an opening parenthesis on top of the stack. In case of a closing bracket, check if the stack is empty. If not, pop in a closing parenthesis if the top of the stack contains the corresponding opening parenthesis. If the parentheses are valid, then the stack will be empty once the input string finishes.
To solve a valid parentheses problem optimally, you can make use of Stack data structure. Here you traverse through the expression and push the characters one by one inside the stack. Later, if the character encountered is the closing bracket, pop it from the stack and match it with the starting bracket.
Standard Parentheses - ( ) Broadly speaking, the primary use of parentheses in Python is to call an object. That is the reason why standard parentheses are sometimes called the "call operator." Aside from their main use, parentheses are also used to define generator expressions.
A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that matched(")(")
will return False
.
def matched(str):
count = 0
for i in str:
if i == "(":
count += 1
elif i == ")":
count -= 1
if count < 0:
return False
return count == 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With