元组中的二维坐标列表,必须计算点之间的距离总和

List of 2D coordinates in tuples and have to calculate the sum of distance between the points

import math


def calculate_distance(p):
    if len(p) == 0:
        return len(p)
    else:
        x = [i[0] for i in p]
        y = [i[1]for i in p]
        dist = 0
        distx = 0
        disty = 0
        for i in range(len(x)):
            x1 = x[i-1]
            x2 = x[i]
            distx = (x1-x2)**2
        for v in range(len(y)):
            y1 = y[v-1]
            y2 = y[v]
            disty = (y1-y2)**2
        for j in p:
            dist = math.sqrt(distx + disty)
        return dist
calculate_distance([(2,2), (5,2), (9,2)])

最后一行代码 returns 4 而它应该 return 7 因为总行进距离是 7 个单位。我在我的代码中做错了什么?我必须在没有任何附加模块的情况下执行此操作。

我已经使用高度优化的 numpy and scipy 模块重写了您的代码:

import numpy as np
from typing import *
from scipy.spatial import distance


    def calculate_distance(p: List[Tuple[int, int]])-> float:
            if p is None or len(p) == 0: return 0
            dists: np.ndarray = distance.cdist(p, p, 'euclidean')
            return float(np.sum(np.diag(dists, 1)))
    
    print(calculate_distance([(2,2), (5,2), (9,2)])) # prints 7.0, as expected

如果您对它的工作原理有任何疑问,请随时提问。单击以下任一链接以阅读有关 scipy.spatial.distance, np.diag, and np.sum.

的更多信息

错误是您正在处理所有值。这些值需要一次处理两个,然后添加距离。一个简单的解决方案是:

def calculateAdjDistance(z):
    #calculate distance between the two selected points
    print(z)
    x1 = z[0][0]
    x2 = z[1][0]
    y1 = z[0][1]
    y2 = z[1][1]
    return ((x1-x2)**2 + (y1-y2)**2)**(1/2)


def calculate_distance(p):
    dist = 0
    if len(p) == 0:
        return 0
    else:
        for i in range(0,len(p)-1):
        #select two points at a time
            dist += calculateAdjDistance([list(p[i]), list(p[i+1])])
            #adding the calculated distance to the previous distance
        return dist

            
print(calculate_distance([(2,2), (5,2), (9,2)]))