Advertisement
Guest User

Untitled

a guest
Mar 17th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. import re
  2. from queue import Queue
  3.  
  4. """
  5. http://algo1567.ru/wp-content/uploads/2015/09/4_expressions.pdf
  6. """
  7.  
  8.  
  9. def calculate(formula):
  10.     formula = "".join(formula.split())
  11.     matching = re.findall(pattern, formula)
  12.     tokens = [i for i in matching]
  13.  
  14.  
  15. pattern = r'[A-Z][A-Z0-9]*|!|->|&|\||[()]'
  16. var_patter = r'[A-Z][A-Z0-9]*'
  17. with open("b.txt") as f:
  18.     formula = f.readline()
  19.  
  20. matching = re.findall(pattern, formula)
  21. matching = [i for i in matching]
  22. cursor = 0
  23. sz = len(matching)
  24.  
  25.  
  26. def parse_impl():
  27.     global cursor
  28.     r_a = parse_disj()
  29.     while cursor < sz and matching[cursor] == '->':
  30.         cursor += 1
  31.         r_b = parse_impl()
  32.         r_a = "(->,{},{})".format(r_a, r_b)
  33.     return r_a
  34.  
  35.  
  36. def parse_disj():
  37.     global cursor
  38.     r_a = parse_conj()
  39.     while cursor < sz and matching[cursor] is '|':
  40.         operator = matching[cursor]
  41.         cursor += 1
  42.         r_b = parse_conj()
  43.         r_a = "({},{},{})".format(operator, r_a, r_b)
  44.     return r_a
  45.  
  46.  
  47. def parse_conj():
  48.     global cursor
  49.     r_a = parse_unary()
  50.     while cursor < sz and matching[cursor] is '&':
  51.         operator = matching[cursor]
  52.         cursor += 1
  53.         r_b = parse_unary()
  54.         r_a = "({},{},{})".format(operator, r_a, r_b)
  55.     return r_a
  56.  
  57.  
  58. def parse_unary():
  59.     global cursor
  60.     if matching[cursor] is '!':
  61.         cursor += 1
  62.         r_a = parse_unary()
  63.         return "(!{})".format(r_a)
  64.     elif matching[cursor] is '(':
  65.         cursor += 1
  66.         r_a = parse_impl()
  67.         cursor += 1
  68.         return r_a
  69.     elif re.match(var_patter, matching[cursor]) is not None:
  70.         print("here{}".format(matching[cursor]))
  71.         r_a = matching[cursor]
  72.         cursor += 1
  73.         return r_a
  74.  
  75.  
  76. a = parse_impl()
  77. print(a == '(->,P,(->,(!QQ),(|,(&,(!R10),S),(&,(&,(!T),U),V))))')
  78. print(a)
  79. print('(->,P,(->,(!QQ),(|,(&,(!R10),S),(&,(&,(!T),U),V))))')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement