title: Better codes for ring-finding program in python
body: <p>I wrote a ring detection program in a very stupid way. Can anyone help to improve it? The following code is to find all 5-member rings. I need a general function which is able to find N-member rings, where N is typically less than 10. Thanks a million!</p>
  
  <p>In my problem, I have about 2000 points. Each point connected to several other points, these connected points are stored in <code>neighbor_list</code>. And the <code>point[i].neighbor_list()</code> return a list of the neighbors of point[i]. The idea in the following code is starting from one point, traverse its neighbor list and it's neighbor's neighbor list, and so on, to find the routes/cycles/rings to go back to the original point. The central part of my code is the following, which finds only rings formed by 5 points. I need a general code to find all N-member rings. Please leave a comment if anything is not clear.  </p>
  
  <pre><code>for r0 in range(2000): #ring member 0
      rin.append(r0)
      for r1 in point[r0].neighbor_list():
          rin.append(r1) #ring member 1 
          for r2 in point[r1].neighbor_list():
              if r2 == r0: continue # to avoid the case of a-b-a ...
              else: rin.append(r2)
              for r3 in point[r2].neighbor_list():
                  if r3 == r1: continue
                  else: rin.append(r3)
                  for r4 in point[r3].neighbor_list():
                      if r4 == r2: continue
                      else: rin.append(r4)
                      for r5 in point[r4].neighbor_list():
                          if r5 == r0: 
                              rin.append(r5)
                              rings.append(list(rin)) # find a ring, save it
                              rin.pop()
                          else: continue  
                      rin.pop()
                  rin.pop()
              rin.pop()
          rin.pop()
      rin.pop()
  </code></pre>