鱼C论坛

 找回密码
 立即注册
查看: 1838|回复: 2

求最短距离

[复制链接]
发表于 2017-8-29 11:31:19 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
想写一个方程,def (place,k,locations):
place是一个坐标,
locations 是一个列表包括地点和坐标 [("旅店", 4.4, 0), ("车站", 5, 3.5), ("广场,4,0")]

如果任意输入一个place (x,y), k是返回地点名称的个数。要求距离从小到大排列,也就是(x,y) 到哪个地点的距离最近,利用 根号(x1-x2)^2 + (y1-y2)^2 来求出locations里面每个点与(x,y)的距离。如果k =1, 则显示最近的一个地点,k=2,则显示最近的两个地点,顺序按着距离从小到大排列。如有等距离,则显示第一个出现的最短地点。

例如 place =(0,0), k =1, 最终显示 ["广场"]
        place =(0,0), k =2, 最终显示["广场",“旅店”]

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-8-31 10:19:31 | 显示全部楼层
1. 使用公式“号(x1-x2)^2 + (y1-y2)^2”求出 place 参数与 locations 参数中各个元素的距离

2. 按从小到大的次序重新排序

3. 根据 k 的值返回相关的结果
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-8-31 12:50:42 | 显示全部楼层
小甲鱼 发表于 2017-8-31 10:19
1. 使用公式“号(x1-x2)^2 + (y1-y2)^2”求出 place 参数与 locations 参数中各个元素的距离

2. 按从小 ...

老师,我知道是这个思路,但是代码试不出来。我现在的思路是:

def kclosest(place,k,locations):
    location_list = []
    dist_list = []
    # calculate the distances between place and each location in locations:
    for each in locations:  
        dist = ((place[0]-each[1])**2+(place[1]-each[2])**2)**0.5
        dist_list.extend((each[0],dist))
   
    #find the minimum value of distance in the list, then find the location that
    #corresponds with the distance
    for i in range(len(dist_list)):
        for j in range(len(dist_list)):
            if dist_list[i][1] == min(dist_list):
                location_list.append[dist_list[i][0]]
                dist_list.pop[i]
    #return the first k element, so we need k+1 exclusive
    return dist_list[:k+1][0]

我不确定如何按着距离排列以后,再把对应的地点也写出来。index对不上
谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-23 13:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表