我试图在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]]
我不知道(目前)如何解决这个问题。任何提示或解决方案都是值得欢迎的!
(由我的解析功能,因为它可以帮助人了解结构更好。)
# 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
我建议使用节点对象而不是使用嵌套列表来构建树的简单数据结构,这将使它更具可读性,并且您将能够将更多预订数据和方法放入每个节点。 – 2009-07-15 04:05:57