8.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Transpose a list of lists in Python using itertools
  2. from itertools import zip_longest
  3. def transpose(l):
  4. return zip_longest(*l, fillvalue=None)
  5. grid = [[int(c) for c in s.strip()] for s in open("8.input")]
  6. visible = set()
  7. def get_vis(line):
  8. visible = []
  9. visible.append(0)
  10. visible.append(len(line) - 1)
  11. for i in range(1, len(line) - 1):
  12. if line[i] > max(line[0:i]) or line[i] > max(line[i+1:]):
  13. visible.append(i)
  14. return visible
  15. for y, line in enumerate(grid):
  16. for x in get_vis(line):
  17. visible.add((x, y))
  18. for x, line in enumerate(transpose(grid)):
  19. for y in get_vis(line):
  20. visible.add((x, y))
  21. print("Part 1:", len(visible))
  22. def get_score(base, segment):
  23. if len(segment) == 0:
  24. return 0
  25. score = 1
  26. for s in segment:
  27. if s >= base:
  28. break
  29. score += 1
  30. else:
  31. score -= 1
  32. return score
  33. scores = {}
  34. transposed = list(transpose(grid))
  35. def all_scores(grid, transposed, x, y):
  36. base = grid[x][y]
  37. return get_score(base, grid[x][y+1:]) *\
  38. get_score(base, list(reversed(grid[x][:y]))) *\
  39. get_score(base, list(transposed[y][x+1:])) *\
  40. get_score(base, list(reversed(transposed[y][:x])))
  41. for x in range(0, len(grid)):
  42. for y in range(0, len(grid)):
  43. scores[(x, y)] = all_scores(grid, transposed, x, y)
  44. print("Part 2:", max(scores.values()))