25_constellations.py 795 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env python3
  2. import sys
  3. from itertools import combinations, product
  4. def dist(a, b):
  5. return sum(abs(y - x) for x, y in zip(a, b))
  6. # iteratively make the first constellations
  7. const = []
  8. for line in sys.stdin:
  9. a = tuple(map(int, line.rstrip().split(',')))
  10. for c in const:
  11. if any(dist(a, b) <= 3 for b in c):
  12. c.append(a)
  13. break
  14. else:
  15. const.append([a])
  16. # merge constellations where possible
  17. prevlen = None
  18. while len(const) != prevlen:
  19. prevlen = len(const)
  20. for i, j in combinations(range(prevlen), 2):
  21. c1 = const[i]
  22. c2 = const[j]
  23. if any(dist(a, b) <= 3 for a, b in product(c1, c2)):
  24. const[i] = c1 + c2
  25. const[j] = []
  26. const = list(filter(None, const))
  27. print(len(const))