Created
December 2, 2018 12:05
-
-
Save Dutcho/8e11c799f32b11a9b2d91e3f2b0704ef to your computer and use it in GitHub Desktop.
AoC02.py
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
'''AoC 2018 #02, safari-https://adventofcode.com/2018/day/2 - Olaf, 2 Dec 2018''' | |
import collections, functools, operator, typing | |
with open('AoC02.txt') as file: | |
ids = tuple(map(str.strip, file.readlines())) | |
def freq_counts(s: str) -> typing.Iterable[int]: | |
'''frequency counts >1 that apply to chars in string s | |
>>> ids = 'abcdef bababc abbcde abcccd aabcdd abcdee ababab'.split() # from AoC explanation | |
>>> print(*map(freq_counts, ids)) | |
set() {2, 3} {2} {3} {2} {2} {3}''' | |
return set(collections.Counter(s).values()) - {1} | |
freq_count_counts = collections.Counter() | |
for id in ids: | |
freq_count_counts.update(freq_counts(id)) | |
print('first answer', functools.reduce(operator.mul, freq_count_counts.values())) | |
def equal_but_1(a: str, b: str) -> bool: | |
'''True iff a == b but for 1 position in a and b''' | |
return sum(map(operator.ne, a, b)) == 1 | |
def equal_but_1_pairs(ids: typing.Iterable[str]) -> typing.Iterator[typing.Tuple[str, str]]: | |
'''pairs (a, b) in ids x ids for which a == b but for 1 position in a and b | |
if (a, b) occur in results, (b, a) doesn't by only testing a triangle from the ids x ids square | |
>>> ids = 'abcde fghij klmno pqrst fguij axcye wvxyz'.split() | |
>>> print(*equal_but_1_pairs(ids)) | |
('fghij', 'fguij')''' | |
for i, a in enumerate(ids): | |
for b in ids[i+1:]: | |
if equal_but_1(a, b): | |
yield a, b | |
pairs = tuple(equal_but_1_pairs(ids)) | |
assert len(pairs) == 1, 'AoC suggests unique solution' | |
pair = pairs[0] | |
print('second answer', ''.join(a for a, b in zip(*pair) if a == b)) | |
# --- main | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment