|
@@ -0,0 +1,26 @@
|
|
1
|
+#!/usr/bin/python3
|
|
2
|
+
|
|
3
|
+import re
|
|
4
|
+
|
|
5
|
+# Returns True if x contains an ABBA sequence
|
|
6
|
+abba = lambda x: re.match(r'.*(.)(?!\1)(.)\2\1.*', x)
|
|
7
|
+# Returns all trigrams in x
|
|
8
|
+tris = lambda x: [x[i:i+3] for i in range(len(x) - 2) if '#' not in x[i:i+3]]
|
|
9
|
+# Returns all ABA sequences in x
|
|
10
|
+abas = lambda x: [t for t in tris(x) if t[0] == t[2] and t[1] != t[0]]
|
|
11
|
+# Swaps an ABA trigram into BAB
|
|
12
|
+swap = lambda x: x[1] + x[0] + x[1]
|
|
13
|
+# Returns all hypernet parts (between brackets) of x
|
|
14
|
+hypernet = lambda x: re.sub(r'^.*?\[|\].*?\[|\].*?$', '#', x)
|
|
15
|
+# Returns all supernet parts (outside of brackets) of x
|
|
16
|
+supernet = lambda x: re.sub(r'\[.*?\]', '#', x)
|
|
17
|
+
|
|
18
|
+with open('07.txt', 'r') as file:
|
|
19
|
+ ips = list(map(str.strip, file.readlines()))
|
|
20
|
+ # tls: has at least one ABBA that's not also in its hypernet sections
|
|
21
|
+ tls = set(filter(abba, ips)) - set(filter(lambda ip: abba(hypernet(ip)), ips))
|
|
22
|
+ # ssl: has an ABA in the supernet and a BAB in the hypernet
|
|
23
|
+ ssl = [ip for ip in ips if set(map(swap, abas(supernet(ip)))).intersection(set(abas(hypernet(ip))))]
|
|
24
|
+
|
|
25
|
+ print("Part one: %s" % len(tls))
|
|
26
|
+ print("Part two: %s" % len(ssl))
|