[英]Choosing a random instance from a tree in python
我試圖遍歷一棵樹,找到一個隨機實例,對其進行變異然后退出,但是遞歸有問題。
有關在突變后轉義循環的注意事項,我曾嘗試提出一個異常,但它僅退出子代的迭代並繼續迭代父代。
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
注意:我正在迭代的類看起來像這樣(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
您應該避免將異常處理用於正常流程,而應將其保留用於錯誤處理。
這是一種可能性:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.