Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. import re
  2. import sys
  3.  
  4. pattern = r'[a-zA-Z][a-zA-Z0-9]*|!|->|&|\||[()]'
  5. var_patter = r'[a-zA-Z][a-zA-Z0-9]*'
  6.  
  7.  
  8. def parse_exception(inp):
  9.     matching = re.findall(pattern, inp)
  10.     matching = [i for i in matching]
  11.     cursor = 0
  12.     sz = len(matching)
  13.     if sz is 0:
  14.         return ""
  15.  
  16.     def parse_implication():
  17.         nonlocal cursor, matching, sz
  18.         r_a = parse_disjunction()
  19.         while cursor < sz and matching[cursor] == '->':
  20.             cursor += 1
  21.             r_b = parse_implication()
  22.             r_a = "(->,{},{})".format(r_a, r_b)
  23.         return r_a
  24.  
  25.     def parse_disjunction():
  26.         nonlocal cursor, matching, sz
  27.         r_a = parse_conjunction()
  28.         while cursor < sz and matching[cursor] is '|':
  29.             cursor += 1
  30.             r_b = parse_conjunction()
  31.             r_a = "({},{},{})".format('|', r_a, r_b)
  32.         return r_a
  33.  
  34.     def parse_conjunction():
  35.         nonlocal cursor, matching, sz
  36.         r_a = parse_unary()
  37.         while cursor < sz and matching[cursor] is '&':
  38.             cursor += 1
  39.             r_b = parse_unary()
  40.             r_a = "({},{},{})".format('&', r_a, r_b)
  41.         return r_a
  42.  
  43.     def parse_unary():
  44.         nonlocal cursor, matching, sz
  45.         if matching[cursor] is '!':
  46.             cursor += 1
  47.             r_a = parse_unary()
  48.             return "(!{})".format(r_a)
  49.         elif matching[cursor] is '(':
  50.             cursor += 1
  51.             r_a = parse_implication()
  52.             cursor += 1
  53.             return r_a
  54.         elif re.match(var_patter, matching[cursor]) is not None:
  55.             r_a = matching[cursor]
  56.             cursor += 1
  57.             return r_a
  58.  
  59.     return parse_implication()
  60.  
  61.  
  62. def main():
  63.     sys.setrecursionlimit(2 ** 30)
  64.     formula = []
  65.     with sys.stdin as f:
  66.         for x in f.readline():
  67.             if not x.isspace():
  68.                 formula.append(x)
  69.     print(parse_exception("".join(formula)), end='')
  70.  
  71.  
  72. if __name__ == '__main__':
  73.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement