fork download
  1. def parentheses(brackets):
  2.  
  3. openBrackets = []
  4. closeBrackets = []
  5.  
  6. for char in range(len(brackets)):
  7. if brackets[char] == '(':
  8. openBrackets.append(char)
  9. elif brackets[char] == ')':
  10. closeBrackets.append(char)
  11.  
  12. pairs = []
  13.  
  14. for o in reversed(range(len(openBrackets))):
  15. for c in range(len(closeBrackets)):
  16. if openBrackets[o] < closeBrackets[c]:
  17. pairs.append([])
  18. pairs[-1].append(openBrackets[o])
  19. pairs[-1].append(closeBrackets[c])
  20. closeBrackets.remove(closeBrackets[c])
  21. break
  22.  
  23.  
  24. listBrackets = list(brackets)
  25.  
  26. filter = []
  27.  
  28. for i in range(len(pairs)):
  29. if pairs[i][0]+1 == pairs[i][1]:
  30. filter.append(pairs[i][0])
  31. filter.append(pairs[i][0])
  32. for x in range(len(pairs)):
  33. if pairs[i][0]-1 in pairs[x] and pairs[i][1]+1 in pairs[x]:
  34. filter.append(pairs[i][0]-1)
  35. filter.append(pairs[i][1]+1)
  36.  
  37. for index in sorted(filter, reverse=True):
  38. del listBrackets[index]
  39.  
  40. if not listBrackets:
  41. return 'NULL'
  42. return ''.join(listBrackets)
  43.  
  44.  
  45. print(parentheses('((a((bc)(de)))f)'))
  46. print(parentheses('(((zbcd)(((e)fg))))'))
  47. print(parentheses('ab((c))'))
  48. print(parentheses('(((3)))'))
  49. print(parentheses('()'))
  50. print(parentheses('((fgh()()()))'))
  51. print(parentheses('()(abc())'))
Success #stdin #stdout 0.02s 9992KB
stdin
Standard input is empty
stdout
((a((bc)(de)))f)
((zbcd)((e)fg))
ab(c)
(3)
NULL
(fgh)
(abc)