计算多个点之间的总距离

问题描述 投票:0回答:1

如何使用循环计算列表中多个点之间的距离。

def create_list(x_range,y_range, locations):
  generated_list = []
  for x in range(locations):
    x_range = random.randint(-300,300)
    y_range = random.randint(-300,300)
    generated_list.append([x_range, y_range])
  return generated_list

上面创建了一个随机列表,我需要使用以下代码来计算返回到起点的所有点的总距离:

def calculate_distance(starting_x, starting_y, destination_x, destination_y):
    distance = math.hypot(destination_x - starting_x, destination_y - starting_y)  # calculates Euclidean distance (straight-line) distance between two points
    return distance

这里我需要使用上面的函数使用循环来计算所有点之间的距离,我将如何使用循环来计算所有点之间的距离

python distance
1个回答
0
投票

从对(x, y)对的列表中,您可以

  • 使用itertools.permutations获取此列表内的排列。这是一个包含3个点的示例,通过指定2

    的长度可以获得6个排列
    values  = [(2, 1), (0, 3), (3, 2)]
    
    perm = [((2, 1), (0, 3)),   ((2, 1), (3, 2)),   ((0, 3), (2, 1)), 
            ((0, 3), (3, 2)),   ((3, 2), (2, 1)),   ((3, 2), (0, 3))]
    
  • 用点数呼叫您的calculate_distance

    p1 = (1,2)
    p2 = (2,3)
    dist = calculate_distance(*p1, *p2) #or calculate_distance(p1[0], p1[1], p2[0], p2[1])
    

使用所有这些

values = create_list(300, 300, 3)
for p1, p2 in permutations(values, r=2):
    dist = calculate_distance(*p1, *p2)
    print(p1, p2, dist)

总结起来,在循环中添加一个值进行total+=dist,或使用接受迭代的sum并缩短

values = create_list(300, 300, 3)
total = sum(calculate_distance(*p1, *p2) for p1, p2 in permutations(values, r=2))

使用循环

仅连续的总和

# Way 1 : d(a,b) + d(b,c) + d(c,d) + d(d,e) + d(e,a)
total = calculate_distance(*values[-1], *values[0])  # between  last and first
for i in range(len(values) - 1):
    total += calculate_distance(*values[i], *values[i + 1])
print(total)

所有点的总和

# Way 2: d(a,b) + d(a,c) + d(a,d) + d(a,e) + d(b,c) + d(b,d) + d(b,e) + d(c,d) + d(c,e) + d(d,e)
total = 0
for p1 in values:
    for p2 in values:
        if p1 != p2:
            total += calculate_distance(*p1, *p2)
print(total)
© www.soinside.com 2019 - 2024. All rights reserved.