-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadvent2017_24.py
75 lines (56 loc) · 1.79 KB
/
advent2017_24.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
# http://adventofcode.com/2017
# solution copied from https://github.com/nedbat/adventofcode2017/blob/master/day24.py
import math
import itertools
from functools import lru_cache
from collections import Counter, defaultdict
from pprint import pprint
import csv
import logging as log
import os
import pytest
import queue
LOGLEVEL = os.environ.get("LOGLEVEL", "INFO").upper()
log.basicConfig(level=LOGLEVEL)
TEST_DATA = """\
0/2
2/2
2/3
3/4
3/5
0/1
10/1
9/10
"""
def parse_components(lines):
return [tuple(map(int, line.split("/"))) for line in lines]
def bridges(components, sofar=()):
last_port = sofar[-1][1] if sofar else 0
for i, comp in enumerate(components):
use_comp = None
if comp[0] == last_port:
use_comp = comp
elif comp[1] == last_port:
use_comp = comp[::-1]
if use_comp:
bridge = sofar + (use_comp,)
yield bridge
yield from bridges(components[:i] + components[i + 1 :], bridge)
def strength(bridge):
return sum(sum(pair) for pair in bridge)
def best_bridge(components):
return max(bridges(components), key=strength)
if __name__ == "__main__":
with open("input_advent2017_24.txt") as file:
components = parse_components(file.readlines())
best = best_bridge(components)
print(f"Part 1: the strongest bridge has strength {strength(best)}")
def best_bridge2(components):
"""Find the strongest of the longest bridges."""
return max(bridges(components), key=lambda b: (len(b), strength(b)))
if __name__ == "__main__":
with open("input_advent2017_24.txt") as file:
components = parse_components(file.readlines())
best = best_bridge2(components)
print(f"Part 2: the strongest longest bridge has strength {strength(best)}")