from lib import get_data, ints def mdist(x, y): return sum(abs(a - b) for a, b in zip(x, y)) data = get_data(__file__) xss = [tuple(ints(line)) for line in data.splitlines()] # check if we can use set (even though we didn't end up using sets) assert len(xss) == len(set(xss)) unplaced = list(xss) groups = [[unplaced.pop()]] while unplaced: # see if any start fits into the current group current_group = groups[-1] add = None for u in unplaced: for x in current_group: if mdist(u, x) <= 3: add = u break if add is not None: break if add is not None: # if yes, add the start to that group and see if another one can be # added to the same group unplaced.remove(add) current_group.append(add) else: # if no, create a new group with an unplaced start groups.append([unplaced.pop()]) print(len(groups))