我正在尝试编写一个从命令行初始化的递归函数,该函数采用带有一系列起点,终点和这些点之间距离的文本文件,然后找到从特定起点到特定终点的最短距离点.

例如,文本文件看起来像这样:

a,b,5

a,c,8

b,d,6

c,d,2

d,e,12

d,f,2

e,g,3

f,g,7

并将使用以下内容调用:

python program_name.py a b text_file_name.txt

这个想法是基于我即将开始的下一学期的课程项目,我希望能够从头开始.教授提供了一个广泛的“起始代码”,发现here.

我已经尝试了多种不同的方法来实现递归函数来遍历文本文件并记录和比较点之间的距离,但我似乎无法做到正确.现在我有一个(非常明显不正确的)代码:

if place not in distances:

print('not in')

distances[place] =roads[place]

dist_so_far = distances[place]

dfs(place, 0.0, roads, distances)

elif place in distances and distances[place] <= dist_so_far:

print('less than')

#dfs(place,0.0, roads, distances)

elif place in distances and distances[place] > dist_so_far:

print('greater than')

distances[place] = dist_so_far

dfs(place, 0.0, roads, distances)

我知道这是不对的,我只是认为它的格式是一个很好的起点.我似乎无法理解哪些词典包含哪些和哪些索引要比较.

解决方法:

I just can’t seem to understand which dictionaries contain what and what indexes to compare and it’s driving me wild!

我会在解释starting-point code that your professor posted以及它正在做什么的时候,不给你一个银盘上的解决方案(因为你将通过自己解决它来学到更多).

def read_distances(map_file):

connections = dict()

# ....

return connections

此函数正在构建一个字典,您可以使用该字典查找是否有任何两个点相互连接,以及它们之间的距离.因此,如果输入文本文件中有一行“A,B,5”,则read_distances的结果将创建两个条目,一个用于A的值(“B”,5),另一个用于B的值(“A” ”,5).另请注意,该字典中的每个条目都是连接列表.换一种说法:

# Assume that map_file contained one line: "A,B,5"

distances = read_distances(map_file)

print(distances["A"]) # Will print "[('B',5)]"

print(distances["B"]) # Will print "[('A',5)]"

如果有多个连接,例如如果文本文件包含:

A,B,5

A,C,3

B,C,4

然后你会得到类似的东西:

distances = read_distances(map_file)

print(distances["A"]) # Will print "[('B',5),('C',3)]"

print(distances["B"]) # Will print "[('A',5),('C',4)]"

print(distances["C"]) # Will print "[('A',3),('B',4)]"

因此,当您获得距离[starting_point]时,您将获得与起点有单一连接的所有点的列表.该列表由2元组(即具有2个元素的元组)组成,每个元组都具有结构(other_point,distance_as_int).

我想我会停在这里,因为这可能足以帮助你解决当前的问题,而无需为你解决这个问题. (我刚刚删除了一段我写的“这就是我建议如何解决这个问题”,因为我意识到除非你提出要求,否则我不应该给你帮助.)如果你需要更多的帮助,请发表评论这个答案(或你的问题)我应该收到通知.我很乐意为此提供更多帮助,特别是因为你在课堂开始之前采取正确的方法试图自己解决问题.

更新1:

好的,还有一个提示无法为您解决问题.当您查找距离[starting_point]并获取元组列表时,您将希望遍历该列表,对每个元组执行某些操作.例如.,

connections = distances[start_point]

for connection in connections:

end_point = connection[0]

distance = connection[1]

# Now do something with start_point, end_point, and distance

# Precisely *what* you'll do with them is up to you

该代码可以简化一点,因为Python有一个很好的“元组解包”功能:如果你循环生成元组的东西,比如你的“连接”列表,你可以这样做:

connections = distances[start_point]

for end_point, distance in connections:

# Now do something with start_point, end_point, and distance

# Precisely *what* you'll do with them is up to you

这将自动为您解包元组.请注意,只有当您知道所有元组将具有相同数量的项目(在这种情况下为2)时,此方法才有效.还有一件事我们可以做,就是注意到我们并不真的需要连接变量,因为除了循环之外我们没有使用它.消除它,代码变为:

for end_point, distance in distances[start_point]:

# Now do something with start_point, end_point, and distance

# Precisely *what* you'll do with them is up to you

这是编写特定循环的最清晰,最“Pythonic”的方式.

注意:上面的代码实际上不会按原样运行,因为Python要求任何循环必须至少包含一个语句,并且注释不计为语句.要使代码实际运行,您必须在循环中包含pass语句. pass语句是一个特殊的语句,它只是一个“无操作”,也就是说,它绝对没有任何作用.所以要实际运行上面的代码,在循环中什么都不做,你会写:

for end_point, distance in distances[start_point]:

# Now do something with start_point, end_point, and distance

# Precisely *what* you'll do with them is up to you

pass

并且该循环将被允许,而没有单词pass的代码将产生IndentationError.为了简单起见,我在上面的所有示例中都没有通过,但我认为值得一提的是为什么代码不会按原样运行.

更新2:

根据要求,这是一个可以解决这个问题的功能,这样您就可以逐步完成并了解正在发生的事情.我已经提出了广泛的意见,但没有评论,这只是八行代码.

def dfs(place, dist_so_far, roads, distances):

"""Depth-first search, which may continue from from_place if dist_so_far

is the shortest distance at which it has yet been reached.

Args:

place: Currently searching from here

dist_so_far: Distance at which from_place has been reached

this time (which may not be the shortest path to from_place)

roads: dict mapping places to lists of hops of the form (place, hop-distance)

distances: dict mapping places to the shortest distance at which they

have been reached so far (up to this time).

"""

#FIXME

# Consider cases:

# - We've never been at place before (so it's not in distances)

# - We've been at place before, on a path as short as this one (in distances)

# - We've been here before, but this way is shorter (dist_so_far)

# Consider which are base cases, and which require recursion.

# For the cases that require recursion, what is the progress step?

# First scenario: we've never reached this place before

if place not in distances:

# Right now we only know one way to get to this place,

# so that's automatically the shortest known distance.

distances[place] = dist_so_far

# Second scenario: we've been here before, via a route

# that was shorter than dist_so_far. If so, then any

# roads from here lead to places we've also already

# visited via a shorter route. Any distance we calculate

# right now would just be longer than the distance we've

# already found, so we can just stop right now!

if dist_so_far > distances[place]:

return

# Third scenario: dist_so_far is actually the shortest

# path we've found yet. (The first scenario is actually

# a special case of this one!) We should record the

# shortest distance to this place, since we'll want to

# use that later. Then we'll look at all the roads from

# this place to other places, and for each of those

# other places, we'll make a recursive call to figure

# out more paths.

# Note no "if" statement needed: because of the return

# statement earlier, if we get here, we know that the

# current route is the best one yet known.

distances[place] = dist_so_far

# Now for some recursion:

for other_place, hop_distance in roads[place]:

dist_to_other_place = dist_so_far + hop_distance

dfs(other_place, dist_to_other_place, roads, distances)

# That's it!

是的,那就是它.我针对你提供的样本距离文件运行它,它找到每对点的最短距离.尝试在脑海中逐步运行算法,看看你是否理解为什么这样做.

但是,当您第一次看到这个时,您可能不会立即明白一个关键概念.这个关键概念是:Python字典是持久且可变的.也就是说,如果将字典对象(如本例中的距离字典)传递给函数,并且该函数修改了字典,则会修改传递给函数的字典.

顺便说一句,专业程序员倾向于认为这是一件坏事,因为调用函数不应该意外地修改你的参数.这往往会导致程序中的细微,难以追踪的错误,通常应该避免. (但是,请注意该句中的单词.如果您调用的函数名为add_value_to_dict,那么您可能希望修改字典.)

但是,在这种特殊情况下,通常被认为是不良副作用的字典修改效果是编写高效代码的关键.距离字典用于跟踪我们到目前为止发现的内容,并查看是否还有任何工作要做.由于您希望通过递归调用dfs()来修改它,因此您不会为自己创建细微的错误.但是我不想让你知道这里使用的技术,修改一个作为参数传递给你的函数的字典,总是一个好主意.大多数情况下,它会导致细微的错误,直到几个月后才会发现.

好吧,这可能是足够的解释.看看你是否可以逐步掌握这些代码并理解它.如果有任何令你困惑的事情,请告诉我.

标签:python,python-3-x,recursion

来源: https://codeday.me/bug/20190702/1357280.html

python递归函数代码_python – 进行深度优先搜索的递归函数相关推荐

  1. python反恐精英代码类似的编程_敲代码学Python:CS188之实现深度优先搜索

    先上运行代码后的视频:人工智能导论之深度优先搜索演示https://www.zhihu.com/video/1173641673426378752深度优先搜索演示之大地图https://www.zhi ...

  2. python常用代码_Python常用算法学习(4) 数据结构(原理+代码)-最全总结

    数据结构简介 1,数据结构 数据结构是指相互之间存在着一种或多种关系的数据元素的集合和该集合中数据元素之间的关系组成.简单来说,数据结构就是设计数据以何种方式组织并存贮在计算机中.比如:列表,集合与字 ...

  3. 人工智能学习:python实现迭代加深的深度优先搜索

    人工智能学习:python实现深度优先搜索算法 本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明. 环境: 主机:WIN10 python版本:3.5 开发 ...

  4. python折叠代码_Python实现代码块儿折叠

    Python实现代码块儿折叠 在python中方法和类都是可以折叠的,但是很多时候需要按照实现的功能将一部分代码折叠起来. 可以用着样的注释代码实现: # ''' your code ''' # 很简 ...

  5. python星空代码_python与云星空Web API

    大家都知道,云星空是支持Web API的.在云社区搜查 Python .API 两个关键词,就会出现相应的显示如下. 感谢Cand,给我们提供了这么好的内容. 我这段时间是做数据迁移的,把WISE数据 ...

  6. python递归函数代码_Python递归函数

    参考: 一.递归函数两大要素 --终止条件和递归方程 1.递归方程,即递归调用的方法 递归通俗的说就是在函数内部自己调用自己,如何调用就是递归方程. 以以下的sum(n)求和函数递归实现方式为例,递归 ...

  7. python边缘检测代码_python Canny边缘检测算法的实现

    图像边缘信息主要集中在高频段,通常说图像锐化或检测边缘,实质就是高频滤波.我们知道微分运算是求信号的变化率,具有加强高频分量的作用.在空域运算中来说,对图像的锐化就是计算微分.对于数字图像的离散信号, ...

  8. python常用代码_Python常用算法学习(3)(原理+代码)——最全总结

    1,什么是算法的时间和空间复杂度 算法(Algorithm)是指用来操作数据,解决程序问题的一组方法,对于同一个问题,使用不同的算法,也许最终得到的结果是一样的,但是在过程中消耗的资源和时间却会有很大 ...

  9. python数独代码_Python 解数独(Sudoku)

    闲来有了用python解数独的想法,但由于对复杂些的算法仍是一窍不通,最终算是用简单算法实现了出来. 相关简介: 1.使用的算法很常规,很好理解,有点类似深度优先搜索算法. 2.解常规难度的数独耗时约 ...

  10. python正则表达式代码_python正则表达式的使用(实验代码)

    正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配. Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式. re 模块使 Python ...

最新文章

  1. 一句话反弹shell
  2. 如何利用python爬虫获取网易云音乐某个歌手简介_Python 爬虫获取网易云音乐歌手信息...
  3. mysql使用参数指定用户_mysql-用户账号及权限管理
  4. 安装了虚拟机后mysql用不了_在虚拟机上安装mysql,安装好了并且初始化之后,一直无法启动mysql如何解决?...
  5. python入门:Anaconda和Jupyter notebook的安装与使用
  6. 编程的7个主要步骤:
  7. Java知识点总结(反射-获取类的信息)
  8. (27)System Verilog设计UART接收
  9. 了解JavaScript中的循环缺点和迭代协议
  10. 让hover效果平滑过渡回初始状态?
  11. python建模 决策_决策树python建模中的坑 :ValueError: Expected 2D array, got 1D array instead:...
  12. 滇西应用技术大学有没有计算机专业,学校介绍
  13. 微信壁纸头像小程序(附源码)
  14. 电源设计那些事儿-ppt01
  15. 关于2018后新款 Mac增加T2安全芯片造成无法U盘启动解决办法
  16. mysql 格式化函数总结_Mysql字符串处理函数详细介绍、总结
  17. 无法打开JFrame窗口
  18. 检测设备摄像头、指南针、录音、陀…
  19. HTML 学习手册(常用的标签)
  20. 华云数据加入上海信息技术应用创新联盟!

热门文章

  1. CSS大美集(关于细节)
  2. SVN server
  3. 主键与主键索引的关系
  4. 交互题[CF1103B Game with modulo、CF1019B The hat、CF896B Ithea Plays With Chtholly]
  5. 【8.16校内测试】【队列】【数学】【网络流/二分图最大匹配】
  6. 【C++】std::是什么?
  7. 分享SCI写作经验和一些工具
  8. 实现Singleton模式
  9. 【转载】 扫描二维码自动识别手机APP下载地址
  10. 顺情说好话,耿直讨人嫌