【发布时间】:2017-08-31 13:13:40
【问题描述】:
我要编写一个函数 tourlength(tour,locations),它将总距离作为给定游览的浮点数返回,即游览中位置之间的距离之和。例如游览(“ngv”、“fed square”、“myhotel”)的总距离为 4.0
我的代码:
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def tourlength(tour, locations):
DBP = []
tour_list = [i for i in locations if i[0] in tour]
coordinate = [i[1:] for i in tour_list]
x_coordinate = [i[0] for i in coordinate]
y_coordinate = [i[1] for i in coordinate]
a = 0
b = 1
j = 0
while j <= (len(tour_list)-2):
distances = distance(x_coordinate[a], y_coordinate[a], x_coordinate[b], y_coordinate[b])
DBP.append(distances)
a += 1
b += 1
j += 1
return sum(DBP)
假设我的函数定义为:
tourlength(["ngv", "fed square", "myhotel"], [("ngv", 4, 0), ("town hall", 4, 4),("myhotel", 2, 2), ("parliament", 8, 5.5), ("fed square", 4, 2)]))
返回的值是 4。但是,我的函数返回值 4.82842712474619,这是旅游列表的值 ["ngv", "myhotel", "fed square"]
我知道我的代码确实可以工作,但未能按正确的顺序执行,我认为这是由于这部分:tour_list = [i for i in locations if i[0] in tour] 但我不确定是否在不导入其他内置 python 函数的情况下对其进行调整。
提前致谢
【问题讨论】:
-
只是每个点到点的距离之和
标签: python python-3.x list function