Guest User

Untitled

a guest
Oct 1st, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import re
  2.  
  3. filename = 'input.txt'
  4.  
  5. expressions = []
  6. truths = set()
  7.  
  8. with open(filename) as file:
  9.     lines = file.readlines()
  10.     lines_count = len(lines)
  11.    
  12.     for i in range(lines_count):
  13.         line = lines[i]
  14.         if i < lines_count - 2:
  15.             bools = re.findall('[A-Z]', line)
  16.             operators = re.findall(r'\|\||&&', line)
  17.            
  18.             if len(bools) - len(operators) != 2:
  19.                 raise ValueError('Invalid expression on line #' + str(i + 1))
  20.            
  21.             expr = dict(bools=bools, operators=operators)
  22.             expressions.append(expr)
  23.         elif i == lines_count - 1:
  24.             truths = set(re.findall('[A-Z]', line))
  25.  
  26. while True:
  27.     no_changes = True
  28.    
  29.     for expr in expressions:
  30.         left = expr['bools'][0] in truths
  31.        
  32.         for i in range(len(expr['operators'])):
  33.             op = expr['operators'][i]
  34.             right = expr['bools'][i + 1] in truths
  35.             if op == '&&':
  36.                 left = left and right
  37.             else:
  38.                 left = left or right
  39.  
  40.         if left and expr['bools'][-1] not in truths:
  41.             truths.add(expr['bools'][-1])
  42.             no_changes = False
  43.             break
  44.     if no_changes: break
  45.  
  46. print(sorted(truths))
Advertisement
Add Comment
Please, Sign In to add comment