0

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).

puppyonkik
  • 213
  • 1
  • 7

1 Answers1

3

You can use count, and your code doesn't work because you return too early, and you also, should return True if it is 0, other wise return False:

def match_brackets(s):
    """
    >>> match_brackets('(7 - 4) * (3 + 2)')
    True
    >>> match_brackets('((2 + 5) / (13 +12)')
    False
    """
    return s.count('(') == s.count(')') and all([x < y for x, y in zip([i for i, x in enumerate(s) if x == '('], [i for i, x in enumerate(s) if x == ')'])])

So I simply first check the number of (s and the number )s, if their equivalent, I continue with another statement in the and clause, otherwise return False already, and continuing, the next statement is checking if all (s are before )s, using a zip between two list comprehensions with enumerate (those simply get the indexes of their searching value) and do an outer list comprehension that which simply checks if all of (s are before )s, and then use all to see if they're all True.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/193628/discussion-on-answer-by-u9-forward-how-to-check-if-a-string-contains-matching-pa). – Samuel Liew May 20 '19 at 09:24