13.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from util import get_input, transpose
  2. input = get_input("13.input")
  3. folds = []
  4. numbers = []
  5. for line in input:
  6. if line.startswith("fold along"):
  7. [d, i] = line.split()[2].split("=")
  8. folds.append((d, int(i)))
  9. elif line != "":
  10. [x, y] = line.split(",")
  11. numbers.append((int(x), int(y)))
  12. grid = [['.' for _ in range((max(x for (x, y) in numbers) + 1))] for _ in range(max(y for (x, y) in numbers) + 1)]
  13. for (x, y) in numbers:
  14. grid[y][x] = '#'
  15. def print_grid(grid):
  16. print("\n".join(["".join(row) for row in grid]))
  17. def fold_y(grid, i):
  18. y = i - 1
  19. for dy, row in enumerate(grid[i + 1:]):
  20. grid[y - dy] = ['#' if row[x] == '#' or grid[y - dy][x] == '#' else '.' for x in range(len(grid[0]))]
  21. grid = grid[:i]
  22. return grid
  23. def fold(grid, d, i):
  24. if d == 'y':
  25. grid = fold_y(grid, i)
  26. else:
  27. grid = transpose(grid)
  28. grid = fold_y(grid, i)
  29. grid = transpose(grid)
  30. return grid
  31. for (d, i) in folds:
  32. grid = fold(grid, d, i)
  33. break
  34. print("Task 1:", sum(sum(1 if c == '#' else 0 for c in row) for row in grid))
  35. for (d, i) in folds[1:]:
  36. grid = fold(grid, d, i)
  37. print("Task 2:")
  38. print_grid(grid)