Solutions to Advent of Code 2017 https://adventofcode.com/2017/
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import functools
  2. import itertools
  3. import operator
  4. def reverse_slice(input, start, length):
  5. """Reverses a slice of the input list, wrapping around if necessary."""
  6. output = list(input)
  7. for i, pos in enumerate(range(start, start + length)):
  8. output[pos % len(output)] = input[(start + length - i - 1) % len(output)]
  9. return output
  10. def knot_hash_rounds(lengths, count=1):
  11. """Applies a number of rounds of the knot hash algorithm (see day 10)."""
  12. position, skip, data = 0, 0, list(range(256))
  13. for _ in range(count):
  14. for length in lengths:
  15. data = reverse_slice(data, position, length)
  16. position += length + skip
  17. skip += 1
  18. return data
  19. def group(n, iterable):
  20. """Collates the iterable into groups n items long."""
  21. # https://docs.python.org/3.1/library/itertools.html#recipes
  22. args = [iter(iterable)] * n
  23. return itertools.zip_longest(*args)
  24. def knot_hash(seed):
  25. """The knot has algorithm (day 10). Output is a hex string."""
  26. lengths = list(map(ord, seed.strip())) + [17, 31, 73, 47, 23]
  27. sparse_hash = knot_hash_rounds(lengths, 64)
  28. dense_hash = [functools.reduce(operator.xor, g) for g in group(16, sparse_hash)]
  29. return "".join(f"{c:02x}" for c in dense_hash)
  30. def add_connected_components(sets, links, to_add=None):
  31. """
  32. Updates the given collection of sets to include a new group of connected components.
  33. Existing sets that overlap with the given `links` are removed and conjoined into a new superset along with the
  34. `to_add` items specified. If `to_add` is not specified then the `links` are added in their place.
  35. """
  36. overlapping = [s for s in sets if any(link in s for link in links)]
  37. for overlap in overlapping:
  38. sets.remove(overlap)
  39. sets.append(functools.reduce(set.union, overlapping, set(to_add if to_add is not None else links)))