edit: forgot to mention the original question in the workbook, which was: Write a function that takes a string and checks that it contains matching parentheses i.e (). Return True if it does and False if it doesn’t.
I'm trying to make a small program that checks if a string has matching parentheses. My workbook states "Consider using a variable to keep count of unclosed parentheses: +1 for an opening one and -1 for a closing one. Use this to check you haven’t closed one before you opened one and that all of them have been closed at the end". This should primarily use for loops and string methods.
The doctest should demonstrate what I mean:
def match_brackets(s):
"""
>>> match_brackets('(7 - 4) * (3 + 2)')
True
>>> match_brackets('((2 + 5) / (13 +12)')
False
"""
This is what I've tried so far:
unclosed = 0
opening = "("
closing = ")"
for ch in s:
if ch in opening:
unclosed += 1
return True
elif ch in closing:
unclosed -= 1
return False
return unclosed
But it just returns True every time. I've been trying to figure this out for the past 20 minutes and just can't work my way past it.
I appreciate all help and can provide further information if necessary (although I think what I've provided will be enough).