Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
No combos used; bit messier as a result solution in Clear category for Remove Brackets by kkkkk
def remove_brackets(text):
"""Return text with extraneous brackets removed."""
openers_to_closers = {'[': ']', '(': ')', '{': '}'}
openers = openers_to_closers.keys()
closers = openers_to_closers.values()
# clean_text will hold the text with extraneous brackets removed.
clean_text = []
# Use a stack to find matching nested brackets.
stack = []
for idx, char in enumerate(text):
if char in openers:
stack.append(char)
nested = False
elif stack and char in closers:
opener_to_match = stack.pop()
# A closer was previously found without a new opener, so
# this closer should envelope what we have so far. This
# means the opener is put in front of the text rather than
# adjacent to what we already have.
if openers_to_closers[opener_to_match] == char:
if nested:
clean_text.insert(0, opener_to_match)
else:
clean_text.append(opener_to_match)
clean_text.append(char)
nested = True
# The top of the stack is not a closer for the current
# character, so it goes back onto the stack.
else:
stack.append(opener_to_match)
# Remove any brackets from the stack that no longer has
# a match in the text. This is needed when there are multiple
# repeats of an opener and only one matching closer.
while stack and stack[-1] in openers and \
openers_to_closers[stack[-1]] not in text[idx+1:]:
stack.pop()
return ''.join(clean_text)
April 7, 2020
Comments: