Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A function to validate a character string containing nested matching pairs of brackets
- def myvalid(mystr):
- openlist = "({[<" # List of possible opening brackets
- closlist = ")}]>" # List of corresponding closing brackets
- closexpect = ["-"] * len(mystr) # Will be used to hold the valid close bracket per level
- level = 0 # Initialise a level counter
- for c in mystr: # Examine input string characters one by one
- if c in openlist: # Have we found an opening bracket?
- level += 1 # - yes - go up one level
- idx = openlist.find(c) # get the index position of the opening bracket
- closexpect[level] = closlist[idx] # store the expected closing bracket for this level
- elif c == closexpect[level]: # Have we found the expected closing bracket for this level?
- level -= 1 # - yes - go down one level
- elif c in closlist: # Have we found an unexpected closing bracket?
- return False # - yes - exit with error
- # We have reached the end of the input string. We should be back at level zero
- return not level # level zero returns True, any other level returns False
- print(myvalid('({})({})'))
- print(myvalid('({})([})'))
- print(myvalid('{({})[{}]}'))
- # Results: True, False, True
Add Comment
Please, Sign In to add comment