Created
December 7, 2016 22:21
-
-
Save lackofcheese/32c4ecf4c0680ffdd758442382e18ffc to your computer and use it in GitHub Desktop.
AoC Day 5 in Python: the power of regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
import sys | |
import re | |
ABBA_REGEX = re.compile(r'(.)(?!\1)(.)\2\1') | |
ABA_REGEX = re.compile(r'(?=(.)(?!\1)(.)\1)') | |
def contains_abba(s): | |
return ABBA_REGEX.search(s) is not None | |
def supports_tls(line): | |
split = re.split(r'[\[\]]', line) | |
for i in range(1, len(split), 2): | |
if contains_abba(split[i]): | |
return False | |
for i in range(0, len(split), 2): | |
if contains_abba(split[i]): | |
return True | |
return False | |
def supports_ssl(line): | |
split = re.split(r'[\[\]]', line) | |
abas = set() | |
babs = set() | |
for i, s in enumerate(split): | |
for m in re.finditer(ABA_REGEX, split[i]): | |
if i % 2 == 0: | |
aba = m.group(1) + m.group(2) | |
if aba in babs: | |
return True | |
abas.add(aba) | |
else: | |
bab = m.group(2) + m.group(1) | |
if bab in abas: | |
return True | |
babs.add(bab) | |
return False | |
if __name__ == '__main__': | |
with open(sys.argv[1]) as f: | |
count_tls = 0 | |
count_ssl = 0 | |
for line in f: | |
if supports_tls(line.strip()): | |
count_tls += 1 | |
if supports_ssl(line.strip()): | |
count_ssl += 1 | |
print("TLS count: {}".format(count_tls)) | |
print("SSL count: {}".format(count_ssl)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment