Advent of Code 2020 - Day 2

in   code   ,

Day 2 of AoC 2020 (Password Philosophy) is an easy problem to solve in Python. As always, spoilers ahead.

Part 1 requires us to count the number of a given character in the given password string. The str.count method is perfect for this, and we can check if the count is within a given range as shown below:

counts, char, password = line.strip().split()
lo, hi = map(int, counts.split('-'))
char = char[:-1] # Strip off the trailing colon

part1 += int(lo <= password.count(char) <= hi)

For part 2, the requirement is that either the low index must match the character, or the high index, but not both. The ^ operator works great here. A catch is that the indices in the input are 1-based, so we need to subtract 1 to get to the 0-based indices used in Python strings.

part2 += int((password[lo-1] == char) ^ (password[hi-1] == char))