Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
30-liner: supersonic solution in Speedy category for Remove Brackets by przemyslaw.daniel
'''
This solution always gives the result of the correct size, but sometimes it differs
from the proper one. For Example:
remove_brackets('}[)){][}{]' == '[][]', should be '[{}]' but it is the same size
It is a trade-off between computation time and accuracy.
text = '}]][)[)[{[](({{()([([}](]({{)]((]]]](})}(]][[)]{)[]()}((()](})([{])[(})()]()' + \
'[([}{(]]{)}[((]](}{}{[([(][()]}[{)[(}[}(([(]((}[{()}({(((])]]]]{(](][})[()]{' + \
'))]{{){)})]{{[()}{})[{{](}(][}}[]{))[}[(][[([])[' # 200 characters
remove_brackets(text) # calculated in couple of seconds
'''
from functools import lru_cache
@lru_cache(maxsize=None)
def remove_brackets(text):
from itertools import combinations
brackets, size = ("()", "[]", "{}"), len(text)
if text in brackets:
return text
pairs = [(x, y) for x, y in combinations(range(size), 2)
if text[x]+text[y] in brackets]
rb = remove_brackets
result = [text[x]+rb(text[x+1:y])+text[y]+rb(text[y+1:])
for x, y in pairs]
return max(result[::-1], key=len, default='')
Feb. 23, 2019
Comments: