用Python计算合肥地铁乘车最优乘车路线:暴力方式

2023-12-07 10:50

本文主要是介绍用Python计算合肥地铁乘车最优乘车路线:暴力方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

假设地铁平均速度60km/h,平均换乘耗时5分钟,列车各站停留时间30秒。已知乘车站及下车站,求最优乘车路线。

也就是最少换乘路线与最短路径之间的选择

首先需要准备的数据:

1.合肥1-3号线站点信息,

根据站名获取纬度,进而获取站点距离

2,构建紧邻图graph。(可以向高德索取数据并整理)

def get_location(keyword,city):#获得经纬度keyword = keyword+"(地铁站)"user_agent='Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'headers = {'User-Agent': user_agent}url='http://restapi.amap.com/v3/place/text?key='+keynum+'&keywords='+keyword+'&types=&city='+city+'&children=1&offset=1&page=1&extensions=all'data = requests.get(url, headers=headers)data.encoding='utf-8'data=json.loads(data.text)result=data['pois'][0]['location'].split(',')return result[0],result[1]def compute_distance(longitude1,latitude1,longitude2,latitude2):#计算两个地铁站的距离user_agent='Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'headers = {'User-Agent': user_agent}#url='http://restapi.amap.com/v3/distance?key='+keynum+'&origins='+str(longitude1)+','+str(latitude1)+'&destination='+str(longitude2)+','+str(latitude2)+'&type=3'两点距离url = 'http://restapi.amap.com/v3/direction/transit/integrated?key='+keynum+'&origin='+str(longitude1)+','+str(latitude1)+'&destination='+str(longitude2)+','+str(latitude2)+'&city=合肥&cityd=合肥&strategy=0&nightflag=0&date=2014-3-19&time=22:34'data=requests.get(url,headers=headers)data.encoding='utf-8'data=json.loads(data.text)result=data['route']['distance']return resultdef get_graph():print('正在创建pickle文件...')data=pd.read_excel('./subway.xlsx')#创建点之间的距离graph=defaultdict(dict)for i in range(data.shape[0]):site1=data.iloc[i]['line']if i<data.shape[0]-1:#print(site2)site2=data.iloc[i+1]['line']#如果是共一条线if site1==site2:longitude1,latitude1=data.iloc[i]['longitude'],data.iloc[i]['latitude']longitude2,latitude2=data.iloc[i+1]['longitude'],data.iloc[i+1]['latitude']name1=data.iloc[i]['name']name2=data.iloc[i+1]['name']distance=compute_distance(longitude1,latitude1,longitude2,latitude2)graph[name1][name2]={'line':site1,'distance':distance}graph[name2][name1]={'line':site1,'distance':distance}output=open('graph.pkl','wb')pickle.dump(graph,output)

暴力的解决问题:

1,遍历出所有路径,以及换乘次数,换乘线路,路径距离

2,找到最短路径(也可能是最短距离),和最少换乘路径进行比较

import pickledef find_allPath(graph,start,end,path=[]):path = path +[start]if start == end:return [path]#print(path)paths = [] #存储所有路径    for node in graph[start]:if node not in path:newpaths = find_allPath(graph,node,end,path) for newpath in newpaths:paths.append(newpath)return pathsdef compare_allPath(start,end,path=[]):paths =find_allPath(graph,start,end,path=[])line_num=[]tr_=[]distances=[]for path in paths:line,distance,tr = [],[],[]for i in range(len(path)-1):li=graph[path[i]][path[i+1]]['line']if len(line)==0:line.append(str(li))elif str(li) != line[-1]:line.append(str(li))tr.append(path[i])distance.append(graph[path[i]][path[i+1]]['distance'])line_num.append(line)tr_.append(tr)distances.append(sum([int(d) for d in distance]))tr_num = [len(i) for i in tr_]if distances.index(min(distances)) != tr_num.index(min(tr_num)):#计算最短距离与最少换成的耗时差异#最短路径与最少换乘的距离差距path_dis_diff = distances[distances.index(min(distances))]-distances[tr_num.index(min(tr_num))]#过站数量差异:station_diff = len(path[distances.index(min(distances))])-len(path[tr_num.index(min(tr_num))])#最短路径与最少换乘的换乘距离差距path_tr_num_diff = tr_num[distances.index(min(distances))]-tr_num[tr_num.index(min(tr_num))]#如果距离耗时与换乘时间做比较:假设地铁速度60km/h,换乘耗时5分钟if abs(station_diff)*0.5+abs(path_dis_diff)/1000<path_tr_num_diff*5:path,linen,tr=paths[tr_num.index(min(tr_num))],line_num[tr_num.index(min(tr_num))],tr_[tr_num.index(min(tr_num))]else:path,linen,tr=paths[distances.index(min(distances))],line_num[distances.index(min(distances))],tr_[distances.index(min(distances))]else:path,linen,tr=paths[distances.index(min(distances))],line_num[distances.index(min(distances))],tr_[distances.index(min(distances))]if len(line)>1:print('需要搭乘{}号地铁'.format(','.join(list(linen))))print('换乘站是{}'.format(','.join(tr)))print('路线规划为:','-->'.join(path))else:print('需要搭乘{}号地铁'.format(','.join(list(linen))))print('路线规划为:','-->'.join(path)) return path,linen,trif __name__ == '__main__':global graphfile=open('graph.pkl','rb')graph=pickle.load(file)#compare_allPath('职教城','幸福坝')#compare_allPath('洪岗','包公园')compare_allPath('职教城','幸福坝')

 

该方法是最LOW的方法,下篇将用dijkstra解决最短路径问题

这篇关于用Python计算合肥地铁乘车最优乘车路线:暴力方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/465580

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可