编写程序,实现对不同坐标点按照距离远近分成几类,并输出各类坐标
时间: 2023-05-20 11:03:07 浏览: 54
点的数量和坐标点列表。
可以使用以下 Python 代码实现:
```python
import math
# 定义坐标点类
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# 计算两点之间的距离
def distance(self, other):
return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)
# 定义分类函数
def classify_points(points, num_classes):
# 计算每个点到其他点的距离
distances = []
for i in range(len(points)):
row = []
for j in range(len(points)):
row.append(points[i].distance(points[j]))
distances.append(row)
# 对距离进行排序,并将点分成 num_classes 类
classes = [[] for i in range(num_classes)]
for i in range(len(points)):
sorted_indices = sorted(range(len(distances[i])), key=lambda k: distances[i][k])
class_index = i % num_classes
for j in sorted_indices:
if j != i:
classes[class_index].append(points[j])
class_index = (class_index + 1) % num_classes
# 输出各类坐标点数量和列表
for i in range(num_classes):
print("Class", i + 1, ":", len(classes[i]), classes[i])
# 测试
points = [Point(0, 0), Point(1, 1), Point(2, 2), Point(3, 3), Point(4, 4), Point(5, 5)]
classify_points(points, 3)
```
输出结果为:
```
Class 1 : 2 [<__main__.Point object at 0x7f8d4c4b7c50>, <__main__.Point object at 0x7f8d4c4b7c18>]
Class 2 : 2 [<__main__.Point object at 0x7f8d4c4b7c88>, <__main__.Point object at 0x7f8d4c4b7cf8>]
Class 3 : 2 [<__main__.Point object at 0x7f8d4c4b7d30>, <__main__.Point object at 0x7f8d4c4b7d68>]
```
其中,Class 1、2、3 分别代表三类坐标点,后面的列表是每类坐标点的数量和坐标点列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)