[(9, '['), (25, ']'), (442, '['), (460, ']'), (558, '['), (576, ']'), (608, ']')]
In this list of tuples I am trying to find key of "]" in the end. If you take a closer look values goes like this;
[ => ] => [ => ] => [ => ] => [ => ]
But at last step it goes;
] => ]
I want to find key when this unexpected value appear. How can I do that?
CodePudding user response:
This is a typical matching brackets exercise that is easily solved using the concept of a stack.
from collections import deque
brackets = {"[": "]"}
stack = deque()
for item in data:
val, bracket = item
if bracket in brackets:
stack.append(bracket)
else:
try:
openb = stack.pop()
except IndexError:
print(val)
if brackets[openb] != bracket:
print(val)
>> 608
CodePudding user response:
I think you're looking for something like this:
from itertools import cycle
L = [(9, '['), (25, ']'), (442, '['), (460, ']'), (558, '['), (576, ']'), (608, ']')]
c = cycle(['[', ']'])
for t in L:
if t[1] != next(c):
print(t[0])
break