Advertisement
Guest User

Untitled

a guest
Dec 6th, 2024
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | Source Code | 0 0
  1. from itertools import cycle
  2. from itertools import product
  3. from functools import reduce
  4.  
  5. path = "day_07.txt"
  6. # path = "test.txt"
  7.  
  8. with open(path) as f:
  9.     lines = [l.strip() for l in f.readlines()]
  10.  
  11. p1 = 0
  12.  
  13. solved = set()
  14. for line in lines:
  15.     result, numbers = line.split(':')
  16.     result = int(result)
  17.     numbers = [int(i) for i in numbers.split()]
  18.    
  19.     n_op = len(numbers) - 1
  20.    
  21.     for operators in product('*+', repeat=n_op):
  22.         op = iter(operators)
  23.         calculation = reduce(lambda x, y: x+y if next(op) == '+' else x*y, numbers)
  24.  
  25.         if calculation == result:
  26.             p1 += result
  27.             solved.add(line)
  28.             break
  29.  
  30.  
  31. print("Part 1:", p1)
  32. p2 = p1
  33. def operation(x,y, op):
  34.     if op == '+':
  35.         return x+y
  36.    
  37.     if op == '*':
  38.         return x*y
  39.    
  40.     return int(str(x)+str(y))
  41.  
  42. for line in lines:
  43.     if line not in solved:
  44.         result, numbers = line.split(':')
  45.         result = int(result)
  46.         numbers = [int(i) for i in numbers.split()]
  47.  
  48.         n_op = len(numbers) - 1
  49.  
  50.         for operators in product('*+|', repeat=n_op):
  51.             op = iter(operators)
  52.             calculation = reduce(lambda x, y: operation(x,y, next(op)), numbers)
  53.  
  54.             if calculation == result:
  55.                 p2 += result
  56.                 solved.add(line)
  57.                 break
  58.  
  59. print("Part 2:", p2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement