Genetic Algorithms in Python - Help me, please


#1

I'm having trouble figuring out how to have this code repeat. The code is for a beginning genetic algorithm function on which I am working on. I'm an extreme amateur with code, so if it's something stupid, sorry :slight_smile:

I think I'm close, I have three variants of code both of which are not quite there, but are relatively close (...maybe...).

Here is var_1 of my code:

population_size = int(raw_input('Enter a population size:')) 

def make_organism(length):
    from random import randint
length = int(raw_input('Enter an organism length:'))
org = []
for i in range(length):
        var = randint(0, 1) 
        org.append(var)
new_org = []

for length in range(population_size):
    var_2 = randint(0, 1) 
    new_org.append(var_2)
    print new_org 
This code returns the correct population but not the correct length.

Ex:

Enter a population size: 3

Enter an organism length: 4

[0]

[0, 0]

[0, 0, 0]

Var_2 of my code:

population_size = int(raw_input('Enter a population size:')) 

def make_organism(length):
    from random import randint
length = int(raw_input('Enter an organism length:'))
org = []
for i in range(length):
        var = randint(0, 1) 
        org.append(var)
new_org = []

for length in range(population_size):
    var = randint(0, 1) 
    org.append(length)
    print new_org

This code returns the correct population but does not return anything in the brackets. Prints new_org as many times as the population_size is.

Ex:

Enter a population size: 3

Enter an organism length: 4

[]

[]

[]

Var_3:

population_size = int(raw_input('Enter a population size:')) 


def make_organism(length):
    from random import randint
length = int(raw_input('Enter an organism length:'))
org = []
for i in range(length):
        var = randint(0, 1) 
        org.append(var)
print org
This code will return the correct length with code but not the correct population size.

Ex:

Enter a population size: 3

Enter an organism length: 4

[0, 1, 0, 1]

'orgs' are organisms represented as empty lists. The code generates a random number pattern of 0's and 1's according to bit length, and should return as many random lists as the user inputs population size.

Thanks in advance! :slight_smile:


#2

You can either put your first for loop into the second or put it into another variable and call it under the second for loop, returning the random list and then appending that list to the new_org list.

We'll, there is more you could do but that is the easiest ways without really changing your code.