Working out solutions for Advent of Code
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1234567891011121314151617181920212223242526272829303132333435363738394041
  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
  12. for line in lines:
  13. chars = {}
  14. gota2, gota3 = False, False
  15. for char in line:
  16. if char in chars.keys():
  17. chars[char] += 1
  18. else:
  19. chars[char] = 1
  20. for k,v in chars.items():
  21. if v == 2 and not gota2:
  22. x2 += 1
  23. gota2 = True
  24. if v == 3 and not gota3:
  25. x3 += 1
  26. gota3 = True
  27. if gota2 and gota3:
  28. break
  29. print("Totals: x2 {}, x3 {}".format(x2, x3))
  30. print("Checksum: {}".format(x2 * x3))
  31. if __name__ == "__main__":
  32. lines = []
  33. with open("02in.txt","r") as f:
  34. for line in f:
  35. lines.append(line.strip())
  36. main(lines)