函数可以在其定义中使用不同的参数调用自身吗?
Could a function call itself with different parameters inside its definition?
此函数有3种模式,即'hh' 'ih'和'ho'。
def mutate_add_connection(self, mode = 'hh'):
if mode == 'hh': # hidden --> hidden
node_a = random.choice(self.hidden_nodes_dict.values())
node_b = random.choice(self.hidden_nodes_dict.values())
self.connect_node_pair(node_a,node_b, 'sort')
elif mode == 'ih': # input --> hidden
node_a = random.choice(self.input_nodes_dict.values())
node_b = random.choice(self.hidden_nodes_dict.values())
node_b.set_links((node_a,random.choice([-1, 1])))
elif mode == 'ho': # hidden --> output
node_b.set_links((node_a,random.choice([-1, 1])))
node_a = random.choice(self.hidden_nodes_dict.values())
node_b = random.choice(self.output_nodes_dict.values())
在加连接变异的实践中,我需要用到这3种模式的概率。假设每种模式为 33.33%。
所以我打算在这个函数中添加一个模式'auto'。为了调用上面的3模式"randomly".
def mutate_add_connection(self, mode = 'hh'):
if mode == 'auto':
chosen_mode = random.choice(['hh','ih','ho'])
self.mutate_add_connection(mode=chosen_mode)
# the code above .......
但我不确定这是否是个好主意。你能建议一个更好的方法来实现我的建议吗?谢谢~
虽然递归函数通常有很好的用途,但这里并不真正需要它。只需重新分配 mode
参数。
def mutate_add_connection(self, mode = 'hh'):
if mode == 'auto':
mode = random.choice(['hh','ih','ho'])
# the code above .......
此函数有3种模式,即'hh' 'ih'和'ho'。
def mutate_add_connection(self, mode = 'hh'):
if mode == 'hh': # hidden --> hidden
node_a = random.choice(self.hidden_nodes_dict.values())
node_b = random.choice(self.hidden_nodes_dict.values())
self.connect_node_pair(node_a,node_b, 'sort')
elif mode == 'ih': # input --> hidden
node_a = random.choice(self.input_nodes_dict.values())
node_b = random.choice(self.hidden_nodes_dict.values())
node_b.set_links((node_a,random.choice([-1, 1])))
elif mode == 'ho': # hidden --> output
node_b.set_links((node_a,random.choice([-1, 1])))
node_a = random.choice(self.hidden_nodes_dict.values())
node_b = random.choice(self.output_nodes_dict.values())
在加连接变异的实践中,我需要用到这3种模式的概率。假设每种模式为 33.33%。
所以我打算在这个函数中添加一个模式'auto'。为了调用上面的3模式"randomly".
def mutate_add_connection(self, mode = 'hh'):
if mode == 'auto':
chosen_mode = random.choice(['hh','ih','ho'])
self.mutate_add_connection(mode=chosen_mode)
# the code above .......
但我不确定这是否是个好主意。你能建议一个更好的方法来实现我的建议吗?谢谢~
虽然递归函数通常有很好的用途,但这里并不真正需要它。只需重新分配 mode
参数。
def mutate_add_connection(self, mode = 'hh'):
if mode == 'auto':
mode = random.choice(['hh','ih','ho'])
# the code above .......