Skip to main content

Command Palette

Search for a command to run...

Advent of Code day 2

Published
4 min readView as Markdown

Day two is a password matching exercise. Will we use regex? Or just string manipulation?

I copy over the boiler plate part of my code -- reading in the data:

def read_data():
    with open("day2.txt") as f:
        pass_db = f.read().split('\n')
    return pass_db

The main function:

if n__name__ == “__main__”:
    run_tests()
    day2()

Then I set up the given test case:

def run_tests():
    pass_db = [[1-3 a: abcde],
    [1-3 b: cdefg],
    [2-9 c: ccccccccc]]
    for password in pass_db:
        check_password(pass_db)

and my "day2" routine:

def day2():
    num_good = 0
    pass_db = read_data()
    for password in pass_db:
        num_good += check_password(password)
    print("Part 1: The number of good passwords is: ", num_good)

Now it’s just a matter of writing "check_password" which parses the line and tests the password. I use the ‘split’ and ’count’ method of python strings for this and quickly get the answer -- 1 star done.

Now Part 2. It turns out the number values aren’t actually the minimum and maximum number of times the character can appear but rather indexes of the positions where the letter should appear. Note that there is no zero index -- 1 means first position. One (and only one!) of the positions must contain the letter. Okay, back to work.

I had the “check_password” portion of my code in a single function so I’ll start by copying this function to make a part2 version of it and I push the logic of my "day2" routine down to a "find_soln" routine.

def day2():
    pass_db = read_data()
    find_soln(pass_db)
def find_soln(pass_db):
    num_good = 0
    num_good2 = 0
    for password in pass_db:
        num_good += check_password(password)
        num_good2 += check_password2(password)
    print("Part 1: The number of good passwords is: ", num_good)
    print("Part 2: The number of good passwords is: ", num_good2)

Then I write check_password2. The logic of this problem is easy enough -- just remember to add one to the index if you’re using a zero-based language. (see my solution on github if you're really stuck.)

And I learned (or perhaps relearned) something! Since the letter should only be in one of the positions and not the others we ideally need an XOR -- which Python doesn’t have. But Python does have a bitwise XOR operator ‘^’ so you can just say:

if bool(pwd[ind1] == letter) ^ bool(pwd[ind2] == letter): 
...

Nice and fun. Also, a terrible set of password requirements. Two more stars down and now we wait for day 3.

More from this blog

Python, etc.

23 posts