acclivity

pyValidateBrackets

Aug 26th, 2021 (edited)
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. # A function to validate a character string containing nested matching pairs of brackets
  2.  
  3. def myvalid(mystr):
  4.     openlist = "({[<"                   # List of possible opening brackets
  5.     closlist = ")}]>"                   # List of corresponding closing brackets
  6.     closexpect = ["-"] * len(mystr)     # Will be used to hold the valid close bracket per level
  7.     level = 0                           # Initialise a level counter
  8.     for c in mystr:                     # Examine input string characters one by one
  9.         if c in openlist:               # Have we found an opening bracket?
  10.             level += 1                  # - yes - go up one level
  11.             idx = openlist.find(c)      # get the index position of the opening bracket
  12.             closexpect[level] = closlist[idx]       # store the expected closing bracket for this level
  13.         elif c == closexpect[level]:    # Have we found the expected closing bracket for this level?
  14.             level -= 1                  # - yes - go down one level
  15.         elif c in closlist:             # Have we found an unexpected closing bracket?
  16.             return False                # - yes - exit with error
  17.     # We have reached the end of the input string. We should be back at level zero
  18.     return not level                    # level zero returns True, any other level returns False
  19.  
  20. print(myvalid('({})({})'))
  21. print(myvalid('({})([})'))
  22. print(myvalid('{({})[{}]}'))
  23.  
  24. # Results: True, False, True
Add Comment
Please, Sign In to add comment