Working out solutions for Advent of Code
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

02a.py 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """ Advent of Code 2018
  2. December 02, puzzle 1
  3. """
  4. def main(lines):
  5. """ For each line, count characters.
  6. If any character appears exactly twice, increment x2.
  7. If any character appears exactly three times, increment x3.
  8. Ignore any doubles or triples past the first set.
  9. At the end, multiply x2 by x3 to get the checksum.
  10. """
  11. x2, x3 = 0, 0 # independent counters. Count how many lines had at least one pair/triplet
  12. for line in lines: # iterate over each line in the input file
  13. chars = {} # dictionary to hold character: count values (e.g. a:1, b:2) for the current line
  14. for char in line: # iterate over characters in each line
  15. if char in chars.keys(): # if we've seen the character before in this line
  16. chars[char] += 1 # increment its count in the dictionary by 1
  17. else: # but if we haven't
  18. chars[char] = 1 # then add it to the dictionary
  19. gota2, gota3 = False, False # Do we have at least one pair/triplet in the line?
  20. for k,v in chars.items(): # iterate over the dictionary
  21. if v == 2 and not gota2: # if the count is 2, we have a pair; if we didn't already have one, then
  22. x2 += 1 # increment the "pair" counter by 1, and
  23. gota2 = True # track that we've seen one so we don't accidentally add any more
  24. if v == 3 and not gota3: # if the count is 3, we have a triplet; if we didn't already have one, then
  25. x3 += 1 # increment the triplet counter by 1, and
  26. gota3 = True # track that we've seen one so we don't accidentally add any more
  27. if gota2 and gota3: # if at this point we've seen both a pair and a triplet,
  28. break # we don't need to check any more characters, so break the loop
  29. print("Totals: x2 {}, x3 {}".format(x2, x3)) # print our totals
  30. print("Checksum: {}".format(x2 * x3)) # print the totals multiplied, which is our checksum
  31. if __name__ == "__main__":
  32. lines = [] # an empty list for the lines in the input file
  33. with open("02in.txt","r") as f: # open the file. "with" means we don't have to close it
  34. for line in f: # iterate over the lines in the input file
  35. lines.append(line.strip()) # strip the newline character, then add it to the list
  36. main(lines) # and pass the list to our main function.