In: Computer Science
IN PYTHON
Create a function called biochild.
The function has as parameters the number m and the lists
biomother and biofather.
The biomother and biofather lists contain 0’s and 1’s.
For example: biomother = [1,0,0,1,0,1] and biofather =
[1,1,1,0,0,1]
Both lists have the same length n.
The 0's and 1's represent bits of information (remember that a
bit is 0 or 1).
The function has to generate a new list (child).
The child list must have the same length n.
child is generated by randomly combining part of the child's
information
biomother and biofather.
The first part of the child list will be made up of the first b
bits of biomother
and the second part by the last n-b bits of the biofather.
For example, if b = 3, biomother = [1, 0, 0, 1,0,1] and biofather
= [1,1,1, 0, 0, 1],
then child = [1,0,0,0,0,1].
The value b has to be chosen randomly by the function.
After generating child, each bit in the list is considered for
mutation.
For each bit of child, with probability m the bit is “mutated” by
being replaced by its inverse
(If the bit is 0 it is replaced by 1, and if it is 1 it is replaced
by 0).
Finally, the function returns the list child.
import random
def biochild(n,biomother,biofather): #Function biochild with parameters n,biofather and biomother
b=random.randint(0,n) #Random value of b in range o to length of lists
child=[] #Creating list child
child=random.sample(biofather, b)+random.sample(biomother, n-b) #Generating random part of biofather and biomother in consideration of b
for i in range(n): #Mutating child by altering sequence
if child[i]==0: #If there is 0 replace by 1
child[i]=1
else:
child[i]=0 #if there is 1 replace by 0
return child #return the list
biomother = [1, 0, 1, 0, 1, 1]
biofather = [0, 0, 1, 1, 1, 0]
x=biochild(6,biofather,biomother) #Calling function biochild with parameters
print(x)
Here i have created the biochild function where the parameters are biofather, biomother and n(size). The function firstly create child list by getting random samples from both biofather and biomother with random value b. For the mutation of list I have use for loop and if statement to alter the bits(0=1 and 1-0). Finally the list is return.