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

1234567891011121314151617181920212223242526272829303132
  1. #!/usr/bin/python3
  2. import math
  3. import operator
  4. def steps(start, delta, count):
  5. sign = int(math.copysign(1, delta))
  6. return [start] * count if delta == 0 else range(start + sign, start + delta + sign, sign)
  7. with open('data/01.txt', 'r') as file:
  8. input = file.read()
  9. movement_lookup = {'L': -1, 'R': +1}
  10. direction_lookup = {0: (0, -1), 1: (1, 0), 2: (0, 1), 3: (-1, 0)}
  11. moves = [(movement_lookup[move[0]], int(move[1:])) for move in input.split(', ')]
  12. heading = 0
  13. history = [(0, 0)]
  14. for move in moves:
  15. heading = (heading + move[0]) % 4
  16. delta = list(map(operator.mul, direction_lookup[heading], (move[1], move[1])))
  17. delta_mag = max(abs(delta[0]), abs(delta[1]))
  18. history += zip(steps(history[-1][0], delta[0], delta_mag),
  19. steps(history[-1][1], delta[1], delta_mag))
  20. duplicates = (x for n, x in enumerate(history) if history[:n].count(x) > 0)
  21. overlap = next(duplicates)
  22. print("Part 1: %s ==> %s" % (history[-1], abs(history[-1][0]) + abs(history[-1][1])))
  23. print("Part 2: %s ==> %s" % (overlap, abs(overlap[0]) + abs(overlap[1])))