adventofcode/2022/03/part1.py
2022-12-07 08:10:55 +01:00

55 lines
1.1 KiB
Python

def load(filename):
with open(filename) as f:
for l in f:
s = l.rstrip()
n = len(s)
offset = int(n/2)
c1 = s[0:offset]
c2 = s[offset:]
yield c1, c2
def overlap(c1, c2):
return list(set(c1).intersection(set(c2)))[0]
def priority(c):
n = ord(c)
if ord("a") <= n <= ord("z"):
return n - ord("a") + 1
if ord("A") <= n <= ord("Z"):
return n - ord("A") + 27
raise Exception()
def calcsum(l):
l = [overlap(*x) for x in l]
t = sum([priority(*x) for x in l])
return t
l = list(load("demo.txt"))
assert "".join(l[0]) == "vJrwpWtwJgWrhcsFMMfFFhFp"
assert l[0][0] == "vJrwpWtwJgWr"
assert l[0][1] == "hcsFMMfFFhFp"
assert overlap(*l[0]) == "p"
assert l[1] == ("jqHRNqRjqzjGDLGL", "rsFMfFZSrLrFZsSL")
assert overlap(*l[1]) == "L"
assert l[2] == ("PmmdzqPrV", "vPwwTWBwg")
assert overlap(*l[2]) == "P"
assert overlap(*l[3]) == "v"
assert overlap(*l[4]) == "t"
assert overlap(*l[5]) == "s"
assert priority("a") == 1
assert priority("z") == 26
assert priority("A") == 27
assert priority("Z") == 52
assert calcsum(l) == 157
l = load("data.txt")
print("Sum is:", calcsum(l))