5
\$\begingroup\$

Below is my attempt at Advent of Code 2022 - Day 3 - Part 1. That link will bring you to the problem description.

I'd like to get some feedback on this. I'm new to Python, started working with it for this years challenge in order to learn. I'm quite certain there are better ways to solve this particular problem. I'd appreciate some peer review on alternative solutions to improve my technique.

Problem Text

--- Day 3: Rucksack Reorganization ---

One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged.

Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.

The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).

The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.

For example, suppose you have the following list of contents from six rucksacks:

vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
  • The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p.
  • The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L.
  • The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P.
  • The fourth rucksack's compartments only share item type v.
  • The fifth rucksack's compartments only share item type t.
  • The sixth rucksack's compartments only share item type s.

To help prioritize item rearrangement, every item type can be converted to a priority:

  • Lowercase item types a through z have priorities 1 through 26.
  • Uppercase item types A through Z have priorities 27 through 52.

In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.

Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?

from pathlib import Path
from string import ascii_letters as allAsciiLetters

def buildAsciiDictionary():
    dictionary = {}
    counter = 1
    for i in allAsciiLetters:
        dictionary[i] = counter
        counter += 1
    return dictionary

def readInputsFromFile(filePath):
    inputs = []
    with open(filePath) as file:
        while True:
            line = file.readline().strip()
            if not line:
                break
            else:
                inputs.append(line)
    return inputs

# Attempt 2
def evaluateInputs(inputs, asciiDictionary):
    sum = 0
    duplicateToken = ''
    duplicateFound = False
    for input in inputs:
        # split the string into two equal halves
        firstHalf, secondHalf = input[:len(input)//2], input[len(input)//2:]

        # compare each character in the first half, to every character in the second half
        for character1 in firstHalf:
            if duplicateFound:
                break
            for character2 in secondHalf:
                if character1 == character2:
                    duplicateToken = character1
                    duplicateFound = True
                    sum += asciiDictionary[duplicateToken]
                    break
        duplicateFound = False
    
    return sum

def main():
    print("Welcome to day 3 of AoC")
    pathToFile = Path(__file__).with_name('day3-1_input.txt')
    inputs = readInputsFromFile(pathToFile)
    asciiDictionary = buildAsciiDictionary()
    sum = evaluateInputs(inputs, asciiDictionary)
    print("The sum of duplicated items is: " + str(sum))

main()
\$\endgroup\$
1
  • \$\begingroup\$ The current title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see How do I ask a good question?. \$\endgroup\$
    – BCdotWEB
    Jan 9, 2023 at 10:57

1 Answer 1

2
\$\begingroup\$

Type hints

Use type hints to clearly display what types are accepted by a function, and what types are returned. Disclaimer: These type hits are written using Python 3.11, so you might need to update your python to run with type hints. If that's not possible, simply remove them.

Naming conventions

Function names and variables should be in snake_case, not camelCase.

Building dicts

You can write this function like this instead:

def build_ascii_dictionary() -> dict[str: int]:
    return { value: idx + 1 for idx, value in enumerate(ascii_letters) }

Which is the same as

def build_ascii_dictionary() -> dict[str: int]:
    letter_dict = {}
    for counter, char in enumerate(ascii_letters):
        letter_dict[char] = counter + 1
    return letter_dict

But looks a lot nicer and more compact.

enumerate returns the index of the item and the item in question at that index, so this allows you to use both (and just add 1 to counter since we have to start at 1).

Reading lines from files

Instead of checking yourself if you've reached the end of the file, let python do it for you

def read_inputs_from_file(filepath: str) -> list[str]:
    with open(filepath, 'r') as file:
        return [line.strip() for line in file]

The for line in file automatically terminates at the end of the file automatically, so you don't need to do a check yourself.

Evaluating two strings

I'll post the new function, then explain below

def evaluate_inputs(inputs: list[str], ascii_dict: dict[str: int]) -> int:
    result = 0
    for string in inputs:
        first_half, second_half = string[:len(string) // 2], string[len(string) // 2:]
        char = set(first_half).intersection(second_half).pop()
        result += ascii_dict[char]
    return result

So first, we split the string in half. Next, we convert each string to a set, which is an unordered list of unique elements. We can now utilize sets .intersection function, which returns a set of all letters that are only in both sets. This, granted that you always know only one character is duplicated in each half, allows us to pop the value from that single item set, which will always return the duplicated character.

Format strings

Just a little tid-bit, you can use f"" to place values within strings without having to convert them to strings then appending them.

print("My age is " + str(age))

Is instead

print(f"My age is {age}")

Main Guard

I'm not sure if AdventOfCode runs your file from some external python file or other extraneous case, but when you write your own programs you should always add a main guard. This ensures that your program is run only when that specific file is ran. If not, when you import this file the main() line will run.

if __name__ == '__main__':
    main()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.