目录
过滤和已知点距离较小的点
import numpy as np
def dist(p1, p2):
return np.linalg.norm(np.array(p1) - np.array(p2))
def group_distance(a, b):
# a, b 都是长度为2的点对
return min(
dist(a[0], b[0]) + dist(a[1], b[1]),
dist(a[0], b[1]) + dist(a[1], b[0])
)
def filter_groups(a, b_list, threshold=10):
# 返回距离 >= threshold 的 b 组
return [b for b in b_list if group_distance(a, b) >= threshold]
调用代码:
a = [(0, 0), (0, 2)]
b_list = [
[(1, 0), (1, 2)], # 距离约为 2.0 + 2.0 = 4.0
[(5, 0), (5, 2)], # 距离约为 5.0 + 5.0 = 10.0
[(10, 0), (10, 2)] # 距离约为 10.0 + 10.0 = 20.0
]
result = filter_groups(a, b_list, threshold=10)
print(result)
返回组内距离最大的两组点
import numpy as np
def point_distance(p1, p2):
return np.linalg.norm(np.array(p1) - np.array(p2))
import numpy as np
def point_distance(p1, p2):
return np.linalg.norm(np.array(p1) - np.array(p2))
def top_k_by_inner_distance(b_list, k=2):
# 每组只有两个点
groups_with_dist = [(group, point_distance(group[0], group[1])) for group in b_list]
# 按距离从大到小排序
groups_with_dist.sort(key=lambda x: x[1], reverse=True)
# 拆成两个列表分别返回
top_groups = [group for group, dist in groups_with_dist[:k]]
top_distances = [dist for group, dist in groups_with_dist[:k]]
return top_groups, top_distances
使用例子:
b_list = [
[(1, 0), (1, 2)],
[(5, 0), (5, 5)],
[(10, 0), (10, 10)],
[(3, 3), (6, 7)]
]
result = top_k_by_inner_distance(b_list, k=2)
print(result)
# 输出:
# [[(10, 0), (10, 10)], [(5, 0), (5, 5)]]