patternpythonMinor
Evaluate parenthesis expression for correct nesting and matching parens
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 TrueSolution
- Use
snake_case(matchParens)
- You are checking a property, so I would name your function
has_correct_parensto make it clearer that this function returnTrueorFalse
[i for i in iterable]is a longer way of sayinglist(iterable)soplist = [l for l in pstring]should becomeplist = 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.