# k-means 曼哈顿距离 classkmeans: def__init__(self, m, k): self.m = m # 坐标点个数 self.k = k # 分组个数
# 输入坐标列表 definput_coordinate(self): coordinate_list = [[0for i inrange(2)] for j inrange(self.m)] # 坐标列表 for i inrange(self.m): coordinate_list[i][0], coordinate_list[i][1] = map(int, input().split()) # 输入坐标 return coordinate_list
# 计算相异矩阵 defcalculate_distance(self, coordinate_list): distance_list = [[0for i inrange(self.m)] for j inrange(self.m)] # 相异矩阵列表m*m for i inrange(self.m): for j inrange(i+1): distance_list[i][j] = abs(coordinate_list[i][0] - coordinate_list[j][0]) + abs(coordinate_list[i][1] - coordinate_list[j][1]) return distance_list # 输出相异矩阵 defoutput_distance(self, distance_list): for i inrange(self.m): for j inrange(i+1): # 输出一半矩阵 print(distance_list[i][j], end=' ') print() # 初始分组 defmin_distance1(self, distance_list): k = self.k # 分组个数 klist = [] # 起始中心点id min_distance = [] # 最小距离 min_distance_id = [[0for i inrange(self.m)] for j inrange(k)] # 最小距离对应id列表k*m for i inrange(k): klist.append(int(input())-1) # 输入起始中心点id,从1开始 for i inrange(self.m): mindist = 20# 初始化最小距离(要大于任意两点间距离) for j in klist: if distance_list[i][j] < mindist: mindist = distance_list[i][j] kid = j min_distance.append(mindist) min_distance_id[kid][i] = i+1 return min_distance_id # 更新中心点 defupdate_center(self, coordinate_list, min_distance_id): center_point = [[0for i inrange(2)] for j inrange(self.k)] for i inrange(self.k): count = 0 for j inrange(self.m): mindstid = min_distance_id[i][j] if(mindstid != 0): count += 1 center_point[i][0] += coordinate_list[mindstid-1][0] center_point[i][1] += coordinate_list[mindstid-1][1] center_point[i][0] = round(center_point[i][0]/count, 3) center_point[i][1] = round(center_point[i][1]/count, 3) return center_point
# 再次分组 defmin_distance2(self, coordinate_list, center_point): k = self.k min_distance = [] # 最小距离 min_distance_id = [[0for i inrange(self.m)] for j inrange(k)] # 最小距离对应id for i inrange(self.m): mindist = 20# 初始化最小距离 for j inrange(k): center_distance = abs(coordinate_list[i][0] - center_point[j][0]) + abs(coordinate_list[i][1] - center_point[j][1]) if center_distance < mindist: mindist = center_distance kid = j min_distance.append(mindist) min_distance_id[kid][i] = i+1 return min_distance_id
# 输出分组结果 defoutput_result(self, min_distance_id): for i inrange(self.k): for j inrange(self.m): if min_distance_id[i][j] != 0: print(min_distance_id[i][j], end=' ') print()
if __name__ == '__main__': m = 12# 坐标点个数 k = 3# 分组个数 kme= kmeans(m,k) print('依次输入坐标列表,如 3 4') coordinate_list = kme.input_coordinate() distance_list = kme.calculate_distance(coordinate_list) kme.output_distance(distance_list)