aoc2022/d3.py
2023-12-03 18:20:02 -05:00

66 lines
1.4 KiB
Python

from string import ascii_lowercase, ascii_uppercase
EXAMPLE = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
"""
def let_to_score(cin):
d = {}
for i, c in enumerate(ascii_lowercase):
d[c] = i + 1
for i, c in enumerate(ascii_uppercase):
d[c] = i + 27
return d[cin]
def clean(text: str) -> list[str]:
return list(filter(lambda l: l.strip() != "", text.splitlines()))
def solve(lines: list[str]):
s = 0
for (i, line) in enumerate(lines):
half = len(line) // 2
a, b = line[:half], line[half:]
a = set(a)
b = set(b)
z = a.intersection(b)
l = list(z)[0]
score = let_to_score(l)
s += score
# 8:42
return s
def get_score(l):
s = 0
s = set(l[0]).intersection(set(l[1])).intersection(set(l[2]))
s = list(s)[0]
return let_to_score(s)
def solve2(lines: list[str]):
s = 0
for i in range(0, len(lines), 3):
s += get_score(lines[i:i+3])
return s
def main():
example = clean(EXAMPLE)
print("Example 1:", solve(example))
data = clean(open("i3.txt").read())
print("Solution 1:", solve(data))
example = clean(EXAMPLE)
print("Example 2:", solve2(example))
data = clean(open("i3.txt").read())
print("Solution 2:", solve2(data))
# 13:08
if __name__ == "__main__":
main()