我要写一个函数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函数。
提前致谢
答案 0 :(得分:0)
您遍历位置,因此游览按位置列表排序。我建议您将位置转换为字典,使{"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()]
但是你可以让你的代码更好。这里的词典非常有用
答案 1 :(得分:0)
不使用列表,而是使用这个结构的位置字典(它更具逻辑性):
那是你得到的:
locations = dict()
locations["ngv"] = (4, 0)
locations["town hall"] = (4, 4)
locations["myhotel"] = (2, 2)
locations["parliament"] = (8, 5.5)
locations["fed square"] = (4, 2)
然后,我会这样做:
import math
locations = dict()
locations["ngv"] = (4, 0)
locations["town hall"] = (4, 4)
locations["myhotel"] = (2, 2)
locations["parliament"] = (8, 5.5)
locations["fed square"] = (4, 2)
tour = ["ngv", "fed square", "myhotel"]
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def tourlength(tour, locations):
Distance = 0
# Initial position
X0 = locations[tour[0]][0]
Y0 = locations[tour[0]][1]
# Counter
i = 1
while i < len(tour):
X = locations[tour[i]][0]
Y = locations[tour[i]][1]
# Add the distance
Distance += distance(X0, Y0, X, Y)
# Reset the initial position
X0 = X
Y0 = Y
# Increment counter
i += 1
return Distance
print (tourlength(tour, locations))
编辑:此外,您可以将字典位置放在单独的文件中,或者甚至可以将其导出为csv或其他格式。
为了使算法更强大,您可以检查巡视中的elt是否在位置。此外,您应该使用tour [i] .lower()来删除大写字母。
答案 2 :(得分:0)
您的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)