我正在尝试在 python 中编写一个简单的遗传编程实用程序。但现在我被困在我的树的交叉/配对功能上。树是由嵌套列表构建的,看起来像这样:
# f = internal node (a function), c = leaf node (a constant)
tree1 = [f, [f, [f, c, c], [f, c, c]], [f, [f, c, c], [f, c, c]]]
tree2 = [f, [f, [f, c, c], c], [f, [f, c, c], c]]
我想在每棵树中随机选择一个点进行拆分,然后我希望将每棵树的一个部分组合成一棵新树。还有一个不应超过的最大深度,因此选择不能真正发生在树中的任何地方,因为它可能会创建一个太大的树。下面是一个关于它应该如何工作的例子:
# f:n, where n is the number of arguments the function take
# + split here
tree1 = [f:2, [f:3, a, a, a], a]
# + split here
tree2 = [f:2, [f:2, a, a], [f:1, a]
tree_child1 = [f:2, [f:1, a], a]
tree_child2 = [f:2, [f:2, a, a], [f:3, a, a, a]]
我不知道(目前)如何解决这个问题。任何提示或解决方案都非常受欢迎!
(添加了我的 parse 函数,因为它可以帮助人们更好地理解结构。)
# My recursive code to parse the tree.
def parse(self, node=None):
if not node:
node = self.root
if isinstance(node, list):
function = node[0]
res = []
for child in node[1:function.arity+1]:
res.append(self.parse(child))
value = function.parse(*res) # function
else:
value = node.parse() # constant
return value