Skip to content
advent of code 2020

day 02

password philosophy

approach

each line is split into a (min, max, letter, password) tuple with a couple of split calls. part 1 counts how many passwords contain the letter between min and max times, using str.count.

part 2 reads the same two numbers as 1-based positions instead, and a password is valid when exactly one of those positions holds the letter. that "exactly one" is an xor of two booleans.

the trick

"exactly one of two" is just ^ on the two comparisons.

python
def part2(l = passwords):
    res = 0
    for mn, mx, c, pw in l:
        res += int((pw[mn - 1] == c) ^ (pw[mx - 1] == c))
    return res