0

I have a set of points in the space, each of them is linked to some other: http://molview.org/?q=Decane

For each point I need to find three other points:

  • One to form a bond: first neighbors
  • Second to form an angle: second neighbors
  • Third to form a dihedral angle: third neighbors is best but second if not existing

I have a working algorithm:

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

This algorithm is using recursivity in a for loop. I use it because I thought recursivity is cool and also because it instantly worked. I assumed that python would finish the for first and then run another function, but after some debugging I realized that it's not working like that. Sometimes the for is running multiples times before another function sometimes not

I googled and it's apparently a bad practice to use such algorithms, would someone be able to explain?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Okano
  • 232
  • 2
  • 9

1 Answers1

0

Each time your for loop gets to the last line it calls the function again, starting the for loop again and so on.

The issue is that the for loop in all of those functions calls has not finished executing, it has executed once, and put a new function call on the stack for search_and_build and each search_and_build execution will do the same while there's still something in your dict.

By the time you get back to the first For loops the dict that's getting iterated on doesn't exist or has shrunk a lot, but there was supposed to be something/more of something to iterate over when it first started.

Basicly recursion is cool, but it makes thing pretty hard to get your head around or debug, even more if you invole other loops inside each steps of your recursion.

TLDR : Mutating and iterable while looping over it is very bad.

gountaa
  • 39
  • 5