Skip to the content.

Day 5: Doesn’t He Have Intern-Elves For This?

Part 1

Santa needs help figuring out which strings in his text file are naughty or nice.

A nice string is one with all of the following properties:

For example:

0. Load Puzzle input

file = open('puzzle.aoc', 'r')

1. Define rules

def more_than_two_vowels(input):
    """Check if more than two vowels are in string"""
    vowels = input.count('a') + input.count('e') + input.count('i') + input.count('o') + input.count('u')
    return vowels > 2

def two_letters_in_a_row(input):
    """Check if one letter follows itself at least once"""
    prev = ''
    for current in input:
        if prev == current:
            return True
        prev = current
    return False

def does_not_contain_forbidden_seqs(input):
    """Does not contain 'ab', 'cd', 'pq' or 'xy'"""
    appearances = input.count('ab') + input.count('cd') + input.count('pq') + input.count('xy')
    return appearances == 0

Task 1: How many strings are nice?

2. Count nice strings

nice_strings = 0

while True:
    line = file.readline()
 
    if more_than_two_vowels(line) and \
        two_letters_in_a_row(line) and \
        does_not_contain_forbidden_seqs(line):
        nice_strings += 1
        
    # if end of file is reached
    if not line:
        break

3. Show nice Strings

nice_strings

4. Close file

file.close()

Part 2

0. Load puzzle input

file = open('puzzle.aoc', 'r')

Realizing the error of his ways, Santa has switched to a better model of determining whether a string is naughty or nice. None of the old rules apply, as they are all clearly ridiculous.

Now, a nice string is one with all of the following properties:

For example:

1. Define new rules

def pair_appears_twice(input):
    """Contains two appearances of pairs"""
    for i in range(len(input)):
        if input[i+2:].count(input[i:i+2]) > 0:
            return True
    return False

def pair_is_seperated(input):
    """Check if a pair is seperated through another character"""
    preprev = '\0'
    prev = ''
    for current in input:
        if preprev == current:
            return True
        preprev = prev
        prev = current
    return False

Task 2: How many strings are nice under these new rules?

2. Count nice strings

nice_strings = 0

while True:
    line = file.readline()
 
    if pair_appears_twice(line) and \
        pair_is_seperated(line):
        nice_strings += 1
        
    # if end of file is reached
    if not line:
        break

3. Show amount of nice strings

nice_strings

4. Close file

file.close()