On Mon, 10 Mar 2025, John Cowan wrote:
I was working at the whiteboard during a job interview
once. I had been
asked to write a function to report if its input had balanced parentheses.
No problem: I wrote an RD parser in Python (which I prefer for
whiteboarding) to detect balance and return True if the parse was successful
and False if EOF was reached.
RD is a bit over the top, isn't it?
Pseudocode:
set counter to 0
while !EOF
do
read char
char == "(" -> counter++
char == ")" -> counter--
abort "Unbalanced: )" if counter < 0
done
abort "Unbalanced: (" if counter > 0
Untested, of course :-)
-- Dave