I have a class named Individual, and I have a function based on it. When I run I get
---> 13 population: list[Individual], elite_size=0.1, new_pop=0.2
TypeError: 'type' object is not subscriptable
How can I get this to work?
def selection_rank_with_population_replacement_elite(
population: list[Individual], elite_size=0.1, new_pop=0.2
) -> list[Individual]:
sorted_individuals = sorted(population, key=lambda ind: ind.get_sharpe(), reverse=True)
best_n_individuals = int(np.floor(len(sorted_individuals) * elite_size))
new_individuals = int(np.floor(len(sorted_individuals) * new_pop))
rank_distance = 1 / len(population)
ranks = [(1 - i * rank_distance) for i in range(len(population))]
ranks_sum = sum(ranks)
selected = sorted_individuals[:best_n_individuals]
for i in range(len(sorted_individuals) - best_n_individuals - new_individuals):
shave = random.random() * ranks_sum
rank_sum = 0
for i in range(len(sorted_individuals)):
rank_sum = ranks[i]
if rank_sum > shave:
selected.append(sorted_individuals[i])
break
new_individuals = [Individual.create_random() for _ in range(new_individuals)]
selected.extend(new_individuals)
return selected
CodePudding user response:
Your code should work with Python 3.9 , but will not work with 3.8 or earlier.
With 3.8, using typing.List
instead:
from typing import List
def selection_rank_with_population_replacement_elite(
population: List[Individual], elite_size=0.1, new_pop=0.2
) -> list[Individual]:
Ref: https://docs.python.org/3/library/typing.html (search for typing.List
in there)
[
typing.List
is] Deprecated since version 3.9: builtins.list now supports [].