-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
45 lines (38 loc) · 1.29 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import itertools
with open('input.txt', 'r') as file:
data = file.read().strip().splitlines()
lines = []
for x in data:
result, numbers = [y.strip() for y in x.split(':')]
result = int(result)
numbers = [int(y) for y in numbers.split()]
lines.append((result, numbers))
total = 0
for result, numbers in lines:
for operators in itertools.product(['*', '+'], repeat=len(numbers) - 1):
subtotal = numbers[0]
for i, operator in enumerate(operators):
if operator == '*':
subtotal *= numbers[i + 1]
else:
subtotal += numbers[i + 1]
if subtotal == result:
total += result
break
print(total)
total = 0
for result, numbers in lines:
for operators in itertools.product(['*', '+', '||'], repeat=len(numbers) - 1):
subtotal = numbers[0]
for i, operator in enumerate(operators):
if operator == '*':
subtotal *= numbers[i + 1]
elif operator == '+':
subtotal += numbers[i + 1]
else:
concat_result = int(str(subtotal) + str(numbers[i + 1]))
subtotal = concat_result
if subtotal == result:
total += result
break
print(total)