我要写一个函数的旅游长度(旅游,地点),返回的总距离作为一个浮动的给定旅游,即旅行地点之间的距离之和。例如,旅游("ngv“、”馈方“、”我的酒店“)的总距离为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函数的情况下对它进行调整。
提前感谢
发布于 2017-08-31 13:41:48
您的tour_list是基于位置的订单,而不是基于旅游。使用dict更好地实现这一点。
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def tourlength(tour, locations):
DBP = []
coordinates = {}
for item in locations:
coordinates[item[0]] = item[1:]
j = 0
while j <= (len(tour)-2):
dest_1 = tour[j]
dest_2 = tour[j + 1]
distances = distance(coordinates[dest_1][0], coordinates[dest_1][1], coordinates[dest_2][0], coordinates[dest_2][1])
DBP.append(distances)
j += 1
return sum(DBP)发布于 2017-08-31 13:25:19
您在各个地点进行迭代,因此旅游按照位置列表的顺序排列。我建议您将位置转换为字典,类似于{"ngv": (4,0), ..}广告,将行tour_list = [i for i in locations if i[0] in tour]转换为
tour_list = [i for i in tour if i in locations.keys()]但是你可以让你的代码更好。这里的字典很有用
https://stackoverflow.com/questions/45982325
复制相似问题