Skip to content

Instantly share code, notes, and snippets.

@synio-wesley
Last active December 3, 2018 15:29
Show Gist options
  • Save synio-wesley/f46c632ac612e3238ffeaff74ce4ab30 to your computer and use it in GitHub Desktop.
Save synio-wesley/f46c632ac612e3238ffeaff74ce4ab30 to your computer and use it in GitHub Desktop.
AOC 2018 - Day 2 - Python
# Part 1
from collections import Counter
lines = [line.strip() for line in open('day2.txt')]
twos = 0
threes = 0
for line in lines:
counts = {l: c for l, c in Counter([l for l in line]).items()}
twos += 1 if 2 in counts.values() else 0
threes += 1 if 3 in counts.values() else 0
print(str(twos * threes))
# Part 1 - Alternative (no imports)
lines = [line.strip() for line in open('day2.txt')]
twos = 0
threes = 0
for line in lines:
letters = {}
for letter in line:
letters[letter] = letters[letter] + 1 if letter in letters else 1
twosCounted = False
threesCounted = False
for letter in letters:
if letters[letter] == 2 and not twosCounted:
twos += 1
twosCounted = True
elif letters[letter] == 3 and not threesCounted:
threes += 1
threesCounted = True
print(str(twos * threes))
# Part 2
lines = [line.strip() for line in open('day2.txt')]
found = False # just for a bit of optimization when answer has been found
for i in range(0, len(lines)):
if found:
break
a = lines[i]
for j in range(i + 1, len(lines)):
b = lines[j]
diff = 0
k = 0
letters = ""
while diff <= 1 and k < len(a):
if a[k] != b[k]:
diff += 1
else:
letters += a[k]
k += 1
if diff == 1:
print(letters)
found = True
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment