HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Evaluate parenthesis expression for correct nesting and matching parens

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
expressionnestingevaluateparenscorrectforparenthesisandmatching

Problem

Please review this solution for matching parens for correctness and nesting.

def matchParens(pstring):
    plist = [l for l in pstring]
    newlist = []
    if plist[0] == ')' or plist.count('(') != plist.count(')') or plist[-1::] == '(':
        return False
    while len(plist) > 0:
        head, *tail = plist
        if head == '(':
            newlist.append(plist.pop(plist.index(head)))
            right = tail.index(')')
            if isinstance(right, int):
                newlist.append(plist.pop(right))
            else:
                return False
        else:
            return False
    return True

Solution


  • Use snake_case (matchParens)



  • You are checking a property, so I would name your function has_correct_parens to make it clearer that this function return True or False



  • [i for i in iterable] is a longer way of saying list(iterable) so plist = [l for l in pstring] should become plist = list(pstring)



  • The preventive check should be at the start for clarity and efficiency



  • What if you will want to use square / curly / triangular parens in the future? I would use constants:



OPEN_PAREN = '('
CLOSE_PAREN = ')'

Code Snippets

OPEN_PAREN = '('
CLOSE_PAREN = ')'

Context

StackExchange Code Review Q#85859, answer score: 2

Revisions (0)

No revisions yet.