Reputation:
I'm having some trouble mixing two lists together to make a new list of the same length.
So far I have randomly selected two lists from a bunch of lists called parent 1 and parent 2. This is what I have so far but the output_list
line doesn't work.
parent1 = listname[random.randint(1,popsize)]
parent2 = listname[random.randint(1,popsize)]
output_list = random.choice(concatenate([parent1,parent2]), length, replace=False)
print(output_list)
The outcome I want is:
if parent1 = [1,2,3,4,5]
and parent2 = [6,7,8,9,10]
then a possible outcome could be [1,2,3,9,10]
or [1,7,2,5,6]
or [1,2,7,4,5]
.
Anybody have any ideas?
(the context is two sets of genes which breed to form a child with a mix of the parents genes)
Upvotes: 1
Views: 534
Reputation: 5441
When you construct genetic algorithms, it is preferable a value from a parent keeps the same index in child array, like genes in chromosomes.
You can performs that with numpy :
import numpy as np
male = np.random.choice(100, 5) # array([25, 90, 25, 96, 91])
female = np.random.choice(100, 5) # array([98, 19, 17, 78, 29])
np.choose(np.random.choice(2, 5), [male, female])
# array([98, 19, 25, 96, 29])
np.choose(np.random.choice(2, 5), [male, female])
# array([25, 90, 25, 78, 29])
Upvotes: 0
Reputation: 12990
You can use random.shuffle
after concatenating parent_1
and parent_2
and pick a slice of the same length as parent_1
:
import random
parent_1 = [1,2,3,4,5]
parent_2 = [6,7,8,9,10]
c = parent_1 + parent_2
random.shuffle(c)
result = c[:len(parent_1)]
print(result) # [4, 5, 10, 6, 9]
Upvotes: 3