kAldown

parenthesis

Nov 11th, 2017
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. import re
  2.  
  3. container = {
  4.     'parenthes': 0,
  5.     'bracket': 0,
  6.     'brace': 0,
  7. }
  8.  
  9. def close(element_type):
  10.     if container[element_type] == 0:
  11.         raise Exception('closing more than opening')
  12.     container[element_type] -= 1
  13.  
  14. def open(element_type):
  15.     container[element_type] += 1
  16.  
  17. parenthes_map = {
  18.     ']': (close, 'bracket'),
  19.     ')': (close, 'parenthes'),
  20.     '}': (close, 'brace'),
  21.     '[': (open, 'bracket'),
  22.     '(': (open, 'parenthes'),
  23.     '{': (open, 'brace'),
  24. }
  25.  
  26. s = 'some(bla)blasl][, no this is (b)labl)e {skajdklsfj} {ksalfj)'
  27. #s = 'some(bla)blasl[], no this is (b)labl()e {skajdklsfj} {ksalfj}'
  28.  
  29. r = re.compile(r'[\(\)\[\]\{\}]+?')
  30.  
  31. result = r.findall(s)
  32.  
  33. for elem_type in result:
  34.     func, element = parenthes_map[elem_type]
  35.     func(element)
Advertisement
Add Comment
Please, Sign In to add comment