lundi 8 juin 2020

Choosing elements in an array randomly - satisfying conditions

I need help for my project. The following are the sample data.

populations = [[1 1]
               [1 1]
               [1 0]
               [1 1]]

score = [0, 4, 0, 6]
avail_res = [4, 4]

Code looks like this:

chromosome = []
for num in score:
    if num <= avail_res[0] and num != 0:
        chromosome = populations[score.index(num)]
        print(chromosome)

        if len(chromosome) > 1:
           k = random.choice(chromosome)
           chromosome_best = [k[1]]
           print(chromosome_best)

        else:
           chromosome_best = [chromosome]
           print(chromosome_best)

The objective is to find the best chromosome among the chosen chromosome/s. For the example above, since only 4 (score index 1) satisfies the condition in the code, it should give chromosome best = [1 1] from populations. In cases that there are more than one score that satisfy the condition, the code should choose the best_chromosome, randomly. For example, score = [4, 2, 2, 6]. I have three elements in score that satisfy the condition (4, 2, 2). Now, in choosing the best_chromosome in populations, the code can choose the one that is higher, which is 4 and give the corresponding value in populations.

The problem is whenever I try to run the code, for the chosen chromosome_best = [1 0] (just an example), The length that I am getting is 2, which corresponds for 1 and 0. But my intent is just to get length = 1 for [1 0] and 3 if the chromosomes are [1 0] [1 1] [1 0]. In this way, I could use the code above and choose randomly.

Any help/suggestion would be appreciated! Thanks!




Aucun commentaire:

Enregistrer un commentaire