blob: 31bd337b1806e05bb46b88731dec7ee27b4cab3b (
plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
#!/usr/bin/python
from itertools import permutations
def parse_input(lines):
data = {}
for l in lines:
words = l.split()
name1 = words[ 0]
name2 = words[10].rstrip(".")
if words[2] == "gain":
score = int(words[3])
else: # words[2] == "lose"
score = -int(words[3])
if name1 not in data:
data[name1] = {}
data[name1][name2] = score
return data
def best_score(data):
names = list(data.keys())
perms = permutations(names)
scores = []
for p in perms:
score = 0
for i in range(len(p)):
n1 = p[i]
n2 = p[(i + 1) % len(p)]
score += data[n1][n2] + data[n2][n1]
scores.append(score)
return max(scores)
def solve_part1(lines):
data = parse_input(lines)
return best_score(data)
def solve_part2(lines):
data = parse_input(lines)
data["Myself"] = {}
names = list(data.keys())
for n in names:
data["Myself"][n] = 0
data[n]["Myself"] = 0
return best_score(data)
def main():
# Read happiness relations from input text file
with open("input.txt", "r") as f:
lines = f.read().splitlines()
print("Part 1 solution:", solve_part1(lines)) # 709 for me
print("Part 2 solution:", solve_part2(lines)) # 668 for me
if __name__ == "__main__":
main()
|