You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 line
2.0KB

  1. import builtins
  2. import collections
  3. import functools
  4. import hashlib
  5. import importlib
  6. import itertools
  7. import math
  8. import operator
  9. import os
  10. import re
  11. import string
  12. import sys
  13. from pathlib import Path
  14. product = functools.partial(functools.reduce, operator.mul)
  15. def render(grid, brush=None):
  16. if brush is None:
  17. brush = {v: v for v in grid.values()}
  18. if isinstance(brush, str):
  19. brush = {i: c for i, c in enumerate(brush)}
  20. xmin, *_, xmax = sorted(int(p.real) for p in grid)
  21. ymin, *_, ymax = sorted(int(p.imag) for p in grid)
  22. brush[None] = ' '
  23. rendered = ''
  24. for y in range(ymin, ymax + 1):
  25. for x in range(xmin, xmax + 1):
  26. rendered += brush[grid.get(complex(x, y))]
  27. rendered += '\n'
  28. return rendered
  29. def read_image(text):
  30. grid = collections.defaultdict(str)
  31. for y, line in enumerate(text.splitlines()):
  32. for x, cell in enumerate(line):
  33. grid[complex(x, y)] = cell
  34. return grid, x + 1, y + 1
  35. def shortest_path(start, end, move):
  36. seen = {}
  37. edge = {start: None}
  38. while edge:
  39. seen.update(edge)
  40. edge = {
  41. adj: pos
  42. for pos in edge
  43. for adj in move(pos)
  44. if adj not in seen
  45. }
  46. if end in seen:
  47. break
  48. else:
  49. raise RuntimeError('Path not found', seen)
  50. path = []
  51. while end:
  52. path.append(end)
  53. end = seen[end]
  54. return path[::-1]
  55. def batch(iterable, size):
  56. count = itertools.count()
  57. for _, sub in itertools.groupby(iterable, lambda _: next(count) // size):
  58. yield sub
  59. def md5(string):
  60. return hashlib.md5(string.encode()).hexdigest()
  61. def loop_consume(lines, handler):
  62. instructions = collections.deque(lines)
  63. count = 0
  64. while instructions:
  65. ok = handler(instructions[0])
  66. if ok:
  67. instructions.popleft()
  68. count = 0
  69. elif count < len(instructions):
  70. instructions.rotate(1)
  71. count += 1
  72. else:
  73. raise RuntimeError('Reached steady state')