【问题标题】:Python function works but has the wrong orderPython函数有效但顺序错误
【发布时间】: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


【解决方案1】:

您的 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)

【讨论】:

  • hmmm 我尝试过这个,但它失败了该函数的 3 个隐藏输入之一。但是,它能够为问题返回正确的值。谢谢顺便说一句(我花了很长时间才知道如何定义元组的字典键,但现在我明白了)!!!
【解决方案2】:

您遍历位置,因此游览按位置列表中的顺序排列。我建议您将位置变成字典,看起来像 {"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()]

但是你可以让你的代码变得更好。这里的字典很有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2014-04-21
    • 2017-08-11
    • 2020-07-08
    • 2020-09-29
    • 2022-11-14
    相关资源
    最近更新 更多