在python中使用递归"for"函数探索链接点



我在空间中有一组点,每个点都链接到其他点:http://molview.org/?q=Decane

对于每个点,我需要找到另外三个点:

  • 一个形成纽带:第一邻居
  • 形成角度的第二个:第二个邻居
  • 第三个
  • 形成二面角:第三个邻居是最好的,但如果不存在,则次

我有一个有效的算法:

def search_and_build(index, neighbor):
#index is the currently selected point, neighbor is a list containing all the connected point...
#if the index is already done return directly
if is_done(index):
return
set_done(index)    
for i, j in enumerate(neighbor):
#add function are adding data in dictionaries and search function are searching in the bonding dict for second and third neighbors
add_bond(j, index)
add_angle(j, search_angle(j))
add_dihedral(j, search_dihedral(j))
search_and_build(j, get_sorted_neighbors(j))

此算法在for循环中使用递归性。我使用它是因为我认为递归很酷,也因为它立即起作用。我假设 python 会先完成for,然后运行另一个函数,但经过一些调试后,我意识到它不是那样工作的。有时 for 在另一个函数之前运行多次,有时不会

我用谷歌搜索了一下,使用这样的算法显然是一种不好的做法,有人可以解释吗?

每次 for 循环到达最后一行时,它都会再次调用该函数,再次启动 for 循环,依此类推。

问题是所有这些函数调用中的 for 循环尚未完成执行,它已经执行了一次,并在堆栈上放置一个新的函数调用以供search_and_build,并且每次执行search_and_build都会执行相同的操作,而您的字典中仍有某些内容。

当你回到第一个 For 循环时,正在迭代的字典不存在或已经缩小了很多,但是当它刚开始时应该有一些/更多的东西需要迭代。

基本上递归很酷,但它会使事情变得非常困难或调试,如果您在递归的每个步骤中涉及其他循环,则更是如此。

TLDR :在循环时发生变异和可迭代是非常糟糕的。

最新更新