Reputation: 83
I'm trying to make it so when I run my code that the parents from the array of parents are only used once. I have shortened the numbers just for troubleshooting. I want my program to select from my array one single possible combination. Once that single element is picked I want it to be unusable again.
The code I'm currently using:
#Importing the needed functions
import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt
import random
from itertools import permutations as permutation
#Defining my mating function where I want each parent in the parent array to be only once and not repeat.
def mating (parents):
parent1 = 0
parent2 = 0
parent1 = permutation(parents,2)
parent2 = permutation(parents , 2)
print ("parent1: ", list(parent1))
print ("parent2: ", list(parent2))
#Function used to create my 4 parents and 3 genes
def generateRandom(population , m):
Population = np.random.rand (population,m)
return(Population)
# main code where I am setting returns from the functions to other vairables to call later
for i in range(2):
candidateSolution = generateRandom(4,3)
print ("the solutions: ", candidateSolution)
full_population = mating(candidateSolution
The output I get now is a permutation where element 0 is used against element 1, 2 ,3.
What I would like it to do is have a random parent assigned to parent 1 and a random non-used parent to be parent 2. I'd like to use each parent only once.
A topic I was looking at that showed what I was getting was: Pair combinations of elements in dictionary without repetition
However, they wanted to have it where element 0 is being used multiple times. I want it to be used only once.
Upvotes: 0
Views: 1157
Reputation: 83
The code used to fix this issue was:
for i in range (int(len(parents)/2)):
parent1 = parents[i]
parent2 = parents[-i-1]
print ("Parent1: ", parent1)
print ("parent2: ",parent2)
This works for the fact that my length was going to be a even number.
Upvotes: 0
Reputation: 500
Instead of selecting unique random combinations in an ordered list, you may select defined items in an shuffled list. This way, you are sure of the unicity of the parents and guarantee the randomness for the breeding.
from random import shuffle
parents = [i for i in range(10)]
shuffle(parents)
n = len(parents)
couples = [(parents[i], parents[n-i-1]) for i in range(int(n/2))]
print(couples)
# an output obtained [(8, 7), (5, 2), (6, 9), (1, 0), (4, 3)]
Adapting to your routine, it turns into:
def mating(parents):
n = len(parents)
parents_1 = parents[:int(n/2)]
# a small security if n is not even
if n == 2*int(n/2):
parents_2 = parents[int(n/2):]
else:
parents_2 = parents[int(n/2):-1]
print("parent1: ", list(parents_1))
print("parent2: ", list(parents_2))
return parents_1, parents_2
Upvotes: 1