Iam trying to iterate through a tree, find a random instance, mutate it then exit but am having problems with recursion.
Note concerning escaping the loop after mutation I have tried raising an exception but it just exits the iterations of children and keeps iterating the parents.
import random as random
rnd=random.random
class Found(Exception): pass
def displayRandomNode(self,indent=0,probchange=0.1):
try:
if rnd()<probchange:
raise Found
elif hasattr(self,"children"):
for c in self.children:
displayRandomNode(c,indent+1,probchange)
except Found:
if type(self)==float: pass
else:
print (' '*indent),self
Note: The classes I am iterating though look like this,(the fw class is not altered directly only its instance within the children), the class node may have children of all three classes in a list.
class node:
def __init__(self,fw,children):
self.function=fw.function
self.name=fw.name
self.children=children
class paramnode:
def __init__(self,idx):
self.idx=idx
class constnode:
def __init__(self,v):
self.v=v
You should avoid using exception handling for normal flow, keep it for error handling.
Here is a possibility:
def displayRandomNode(self,indent=0,probchange=0.1):
if not hasattr(self,"children") or rnd() < probchange:
return (self, indent)
else:
c = random.choice(self.children)
return displayRandomNode(c,indent+1,probchange)
Here is another, more like your code idea of going through the whole tree with a little probability to exit at each node. Beware that it may exit without finding anything.
def displayRandomNode(self,indent=0,probchange=0.1):
if rnd() < probchange:
return (self, indent)
elif hasattr(self,"children"):
res = None
for c in self.children:
res = displayRandomNode(c,indent+1,probchange)
if res:
break
return res
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.