Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using ord solution in Clear category for Remove Brackets by quarkov
"""
ord("(") == 40, ord(")") == 41
91, 93, 123 and 125 are for "[", "]", "{" and "}" respectively
It's too sad "]" doesn't follow "[" that's why there're two conditional
statements to check if a bracket is in "([{"
"""
def remove_brackets(brackets):
stack, matching = [], []
counter = {40: 0, 41: 0, 91: 0, 93: 0, 123: 0, 125: 0}
for bracket in brackets:
counter[ord(bracket)] += 1
for pos, bracket in enumerate(brackets):
if bracket == '(' and counter[(ord(bracket)+1)] >= stack.count(bracket) + 1:
stack.extend([bracket, pos])
elif bracket in '[{' and counter[(ord(bracket)+2)] >= stack.count(bracket) + 1:
stack.extend([bracket, pos])
elif bracket in ")]}" and stack and abs(ord(bracket) - ord(stack[-2])) <= 2:
matching.extend([(pos, bracket), (stack.pop(), stack.pop())])
return "".join([bracket for pos, bracket in sorted(matching)])
Feb. 20, 2019
Comments: