The following code is a working solution for the balanced parentheses problem.
I'm really just wondering about coding style here when it comes to separating out related if-statements.
When there are two related if-statements, and where the second is run if the first is run, should I merge all checks into one complete if-statement, as in,
if char in open_close_parens and stack and stack[-1] == open_close_parens[char]:
or separate out the two if-statements as I've done here, with the check for an empty stack (list) then being more prominent in the second follow-up if-statement?
def is_valid(stri: str) -> bool:
stack = []
open_close_parens = {
')':'(',
']':'[',
'}':'{'
}
for char in stri:
if char in open_close_parens:
# if stack is not empty and there is a match, pop it
if stack and stack[-1] == open_close_parens[char]:
stack.pop()
else:
return False
else:
stack.append(char)
return not stack
print(is_valid(']'))
print(is_valid('()'))
if
statements in loop" part of the code requirements, or just an artefact of how you solved the problem? If the latter, I'd recommend removing from the title. \$\endgroup\$