我今天遇到这种表示法 本教程在这里:https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6
parent1_idx = k%parents.shape[0]
右侧将返回什么? 这种表达的名字是什么? 预先感谢!
答案 0 :(得分:1)
%
是python中的运算符,即Modulus operator - it gives remainder of the division of left operand by the right
答案 1 :(得分:1)
我在提到的文章的这段代码中看到了这一行:
for k in range(offspring_size[0]):
# Index of the first parent to mate.
parent1_idx = k%parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1)%parents.shape[0]
parents
的定义如下:
parents = numpy.empty((num_parents, pop.shape[1]))
for parent_num in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
max_fitness_idx = max_fitness_idx[0][0]
parents[parent_num, :] = pop[max_fitness_idx, :]
fitness[max_fitness_idx] = -99999999999
return parents
从以上两行可以很明显地看出k
和parents.shape[0]
都是整数,因此这行是两个数值变量之间的简单modulo operator:a = b % c
。