-
Notifications
You must be signed in to change notification settings - Fork 1
/
day13.py
55 lines (48 loc) · 1.52 KB
/
day13.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
46
47
48
49
50
51
52
53
54
import os.path
import re
import math
from collections import defaultdict
from itertools import permutations
def get_input(filename=None):
if not filename:
filename = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
with open(filename) as fp:
input = fp.read().strip()
return dict(((a,b),int(amount)*(1 if dir=='gain' else -1)) for a,dir,amount,b in (re.search(r'^(\w+) would (lose|gain) (\d+) happiness units? by sitting next to (\w+)\.$', line).groups() for line in input.split('\n')))
# end get_input
def part1(rules):
people = set()
for a,b in rules:
people.add(a)
people.add(b)
max_happiness = None
for order in permutations(people):
happiness = 0
a = order[-1]
for b in order:
happiness += rules.get((a,b),0)+rules.get((b,a),0)
a = b
if max_happiness is None or happiness > max_happiness:
max_happiness = happiness
return max_happiness
# end part1
def part2(rules):
people = set(['Me'])
for a,b in rules:
people.add(a)
people.add(b)
max_happiness = None
for order in permutations(people):
happiness = 0
a = order[-1]
for b in order:
happiness += rules.get((a,b),0)+rules.get((b,a),0)
a = b
if max_happiness is None or happiness > max_happiness:
max_happiness = happiness
return max_happiness
# end part2
if __name__ == '__main__':
rules = get_input()
print part1(rules)
print part2(rules)