大佬求助
用Python随机生成十个点(id,x,y)。计算所有点之间距离,并显示距离最近的两个点的id和两点间距离。嗨,初学者!让我们一起来解决这个问题。首先,我们需要使用Python的random模块生成十个点,每个点包含一个id和x、y坐标。
import random
points = []
for i in range(10):
point_id = i + 1
x = random.randint(0, 100)
y = random.randint(0, 100)
points.append((point_id, x, y))
接下来,我们需要计算所有点之间的距离。我们可以使用两点间的欧氏距离公式来计算两点之间的距离。
import math
def calculate_distance(point1, point2):
x1, y1 = point1, point1
x2, y2 = point2, point2
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
return distance
distances = {}
for i in range(len(points)):
for j in range(i + 1, len(points)):
point1 = points
point2 = points
distance = calculate_distance(point1, point2)
distances[(point1, point2)] = distance
最后,我们需要找到距离最近的两个点及其距离。我们可以使用min函数来找到字典中最小的值,并返回对应的键。
closest_points = min(distances, key=distances.get)
closest_distance = distances
print("距离最近的两个点的id是{}和{},它们的距离是{}".format(closest_points, closest_points, closest_distance))
这样就完成了!完整代码如下:
import random
import math
def calculate_distance(point1, point2):
x1, y1 = point1, point1
x2, y2 = point2, point2
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
return distance
points = []
for i in range(10):
point_id = i + 1
x = random.randint(0, 100)
y = random.randint(0, 100)
points.append((point_id, x, y))
distances = {}
for i in range(len(points)):
for j in range(i + 1, len(points)):
point1 = points
point2 = points
distance = calculate_distance(point1, point2)
distances[(point1, point2)] = distance
closest_points = min(distances, key=distances.get)
closest_distance = distances
print("距离最近的两个点的id是{}和{},它们的距离是{}".format(closest_points, closest_points, closest_distance))
希望这可以帮到你!如果还有其他问题,请随时提问。
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。 {:5_95:}
页:
[1]