Call a recursive function in python as long as a condition is met?


#1

Hi all,

i tried to create a recursive function with python that choose a random point from a nearest points group.
It works but now i want analyze the result and depending on some conditions i want to recall the function.

How can a function can be called again till the conditions is met?

import scriptcontext
import rhinoscriptsyntax as rs
import ghpythonlib.components as gc
import random
import Rhino

visiblept = [startpt]
cullindexin.remove(startpt)



def path(closestpt,cullist):

    # 1
    # choose a random point from nearest points and do this process recursiv
    # store these random points in a list called visiblept
    
    i = gc.ListItem(closestpt,random.choice(closestpt),True)
    visiblept.append(i)
    L = cullist
    L.remove(i)
    P = gc.ClosestPoints(i,L,5)[0]
    
    
    if len(visiblept) <= iterator:
        return path(P,L)

path(closestptin,cullindexin)

# 2
# create a polyline from visiblept and check for self intersection

Curveguid = rs.AddPolyline(visiblept)
Curve = rs.coercecurve(Curveguid)
events = Rhino.Geometry.Intersect.Intersection.CurveSelf(Curve,0.001)


# 3
# if self intersection is True do 1 again till selfintersection is False
# if len(events) > 0:
    # HOW CAN I CALL THE PATH FUNCTION AGAIN

Any help is welcome.


(Tim Stark) #2

I‘m not into Phyton, but wouldn‘t it be a „while loop“ ?

First example on google:
https://www.tutorialspoint.com/python/python_while_loop.htm


#3

Thanks for the tip.
if i try this option ( and i think you are right ) i get a error and i dont know why

# 3
# if self intersection is True do 1 again till selfintersection is False
# if len(events) > 0:
    # HOW CAN I CALL THE PATH FUNCTION AGAIN

while len(events) > 0:
    path(closestptin,cullindexin)

error

Runtime error (ValueErrorException): list.index(item): item not in list

Traceback:
  line 31, in path, "<string>"
  line 54, in script

line 31 : L.remove(i)
line 54 : path(closestptin,cullindexin)


(qythium) #4

Sounds like you’re trying to do recursive backtracking algorithm - look up maze solving and depth-first search algorithms to see how it’s done.

Basically the idea is to keep track of visited nodes on a stack ( last-in first-out), along with some list of possible choices at each node. Then at each step make a choice, mark it as “chosen” and push the next node onto the stack. Keep going until there’s an error condition, then start popping off your stack and making different branching paths from before.


#5

Thansk for your tip, its a lot of stuff .