0

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
4

1 回答 1

1

您应该避免将异常处理用于正常流程,将其保留用于错误处理。

这是一种可能性:

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)

这是另一个,更像是您的代码想法,即以很小的概率在每个节点处退出整个树。请注意,它可能会在没有找到任何东西的情况下退出。

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
于 2013-09-13T13:11:03.717 回答