Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Remove Brackets by mortonfox
PAIRS = [['(', ')'], ['[', ']'], ['{', '}']]
def find_last(lst, c):
i = len(lst) - 1
while i >= 0:
if lst[i] == c: break
i -= 1
return i
# Retain only paired characters and join them into a single string.
sift_and_combine = lambda lst: ''.join(item for item in lst if len(item) > 1)
def remove_brackets(a):
bstack = []
for c in a:
for left, right in PAIRS:
if c == left:
bstack.append(c)
elif c == right:
last_match_index = find_last(bstack, left)
if last_match_index >= 0:
combined = left + sift_and_combine(bstack[last_match_index+1:]) + right
bstack = bstack[:last_match_index] + [combined]
return sift_and_combine(bstack)
if __name__ == '__main__':
print("Example:")
print(remove_brackets('(()()'))
# These "asserts" are used for self-checking and not for an auto-testing
assert remove_brackets('(()()') == '()()'
assert remove_brackets('[][[[') == '[]'
assert remove_brackets('[[(}]]') == '[[]]'
assert remove_brackets('[[{}()]]') == '[[{}()]]'
assert remove_brackets('[[[[[[') == ''
assert remove_brackets('[[[[}') == ''
assert remove_brackets('') == ''
print("Coding complete? Click 'Check' to earn cool rewards!")
Feb. 7, 2019