可以使用yield
,yield from
和send
; 感谢 juanpa.arrivillaga 在评论中提出的建议。
下面的代码在随机二叉树中搜索最多 10 个节点并返回其中的最大值。每当它必须计算heuristic
用于指导搜索的 a 时,它就会中断生成/搜索。
import random
class Node(object):
def __init__(self, heuristic_value):
self.children = {"left": None, "right": None}
self.child_values = heuristic_value
self.value = random.randint(0, 100)
self.terminal = random.random() > 0.9
def add_leaf(self):
if self.terminal:
return self.value
direction = self.select()
if self.children[direction]:
value = yield from self.children[direction].add_leaf()
else:
value = yield from self.expand(direction)
value = self.backup(direction, value)
return value
def select(self):
if self.child_values["left"] > self.child_values["right"]:
return "left"
else:
return "right"
def expand(self, direction):
heuristic_value = yield
child = Node(heuristic_value)
self.children[direction] = child
return child.value
def backup(self, direction, value):
self.child_values[direction] = value
if value > self.value:
return value
else:
return self.value
def heuristic():
return {"left": random.randint(0, 100), "right": random.randint(0, 100)}
tree = Node(heuristic())
for _ in range(10):
gen = tree.add_leaf()
value = None
while True:
try:
gen.send(value)
value = heuristic()
except StopIteration as value:
max_val = value
break
print(f"Largest Value: {max_val}")