Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Stack-based solution in Clear category for Brackets by PositronicLlama
"""Check for proper bracket nesting."""
BRACKET_PAIRS = ['()', '{}', '[]', '<>']
OPEN_BRACKETS = {a for a, _ in BRACKET_PAIRS}
CLOSE_BRACKETS = {b: a for a, b in BRACKET_PAIRS}
def checkio(text):
"""Return whether text has proper bracket nesting."""
stack = []
for c in text:
if c in OPEN_BRACKETS:
stack.append(c)
elif c in CLOSE_BRACKETS:
if not stack or stack[-1] != CLOSE_BRACKETS[c]:
return False
stack.pop()
return not stack
if __name__ == '__main__':
assert checkio('({(asda)sd[s]d})') == True, 'First'
assert checkio('({[a]((s)})') == False, 'Second'
print('All ok')
Jan. 5, 2013
Comments: