find_groups.py 804 B

123456789101112131415161718192021222324252627282930
  1. from itertools import combinations, product
  2. def canMerge (g, h):
  3. for i, j in g:
  4. for x, y in h:
  5. if abs(i - x) <= 1 and abs(j - y) <= 1:
  6. return True
  7. return False
  8. def findGroups (field):
  9. # initialize one-element groups
  10. groups = [[(i, j)] for i, j in product(range(len(field)), range(len(field[0]))) if field[i][j] != ' ']
  11. # keep joining until no more joins can be executed
  12. merged = True
  13. while merged:
  14. merged = False
  15. for g, h in combinations(groups, 2):
  16. if canMerge(g, h):
  17. g.extend(h)
  18. groups.remove(h)
  19. merged = True
  20. break
  21. return groups
  22. # intialize field
  23. field = "drawings/5129275_Rev01-GV12.txt"
  24. groups = findGroups(field)
  25. print((groups)) # 3