DEV Community

Discussion on: AoC Day 5: Alchemical Reduction

Collapse
 
thejessleigh profile image
jess unrein • Edited

My first inclination was to do this recursively. Had to fudge it a bit because doing a truly recursive solution exceeds the max recursive depth :(

Here's my Python for part 1. It's very slow. Gonna look into refactoring to a regex or list comprehension solution for part 2. Kind of ready to move out of string manipulation land either way!

def polymer_compression(polymer):
    components = list(polymer)
    compressed_polymer, changes = find_sets(components)
    while changes is True:
        compressed_polymer, changes = find_sets(compressed_polymer)

    return len(compressed_polymer)

def find_sets(components):
    prev_val = None
    prev_case = None
    changes = False
    for index, component in enumerate(components):
        current_val = ord(component.lower())
        current_case = component.istitle()
        if current_val == prev_val and current_case != prev_case:
            components.pop(index)
            components.pop(index - 1)
            changes = True
            break
        prev_val = current_val
        prev_case = current_case
    return components, changes

print(polymer_compression(open('input.txt', 'r').read()))