[英]Choosing a random instance from a tree in python
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. 注意:我正在迭代的类看起来像这样(fw类不会仅在子类中直接更改其实例),类节点可能在列表中具有所有三个类的子类。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.