The Problem:
I am attempting to write some python code that searches through a list and returns the index of a matching bracket. For example:
array = ["(","foo",")","(","bar","(",")",")"]
f(0) => 2
f(1) => ERROR: Not a bracket.
f(2) => 0
f(3) => 7
My Feeble Attempts:
I tried looping through the list and finding the closest bracket, but then I realised it didn't work when you had loops inside loops (loopception). I have also tried adding a counter that adds one to the counter if it's a new bracket (
and takes one if it's a close bracket )
, then checks to see if it equals -1
, but that doesn't work.
Previous Code:
while True:
if(count == -1):
iterator = j+1
break
else:
j += 1
print j
if(commands[j] == "("):
count += 1
if(commands[j] == ")"):
count -= 1
Where iterator is the input and commands is the array