Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Remove Brackets by dygger
from itertools import takewhile
# just 3 brackets, linear search should be ok
OPEN = '([{'
CLOSE = ')]}'
def remove_brackets(line: str) -> str:
start = sum(1 for _ in takewhile(lambda c: c in CLOSE, line))
end = len(line) - sum(1 for _ in takewhile(lambda c: c in OPEN, reversed(line)))
line = line[start:end]
if is_balanced(line):
return line
result = ''
for i in range(len(line)):
new_line = remove_brackets(line[:i] + line[i + 1:])
if len(new_line) > len(result):
result = new_line
return result
def is_balanced(line: str) -> bool:
stack = []
for bracket in line:
if bracket in OPEN:
stack.append(bracket)
elif stack and OPEN.find(stack[-1]) == CLOSE.find(bracket):
stack.pop()
else:
return False
return not stack
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('') == ''
assert remove_brackets('[(])') == '()'
print("Coding complete? Click 'Check' to earn cool rewards!")
Aug. 27, 2021