Advent of Code: Day 4

For Day 4, the challenge is to calculate the number of valid passphrases given some rules. My Python 2 solution is below:

def is_valid(input, modification=None):
    hsh = set()
    for word in input.split(" "):
        if modification:
            word = modification(word)
        if word in hsh:
            return False
        hsh.add(word)
    return True

with open("input.txt", "r") as o:
    print "Part 1:", len([line for line in o if is_valid(line.strip())])
    print "Part 2:", len([line for line in o if is_valid(line.strip(), modification=lambda w: "".join(sorted(w)))])

Python is a really lovely language for this sort of thing...

Advent of Code runs every day up to Christmas, you should join in!.

Show Comments

Get the latest posts delivered right to your inbox.