Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

92 lines
2.1KB

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