vendredi 8 décembre 2017

Copy item and add it to list based on chance

The function reproduce takes 3 arguments: viruses( a list of viruses). mutationProb(float 0-1 chance to mutate only when reproducing) and reproductionProb(float 0-1 chance to reproduce). So a float of 0.2, 0.4 would give it a 40% to reproduce, and if it reproduces a 20% chance to mutate.

I already wrote the mutate function, it works correctly :

def mutate(virus):
    # choose random index to change
    index = random.randint(0, len(virus) - 1)

    # make sure you are not using the previous char by removing it from 
    # the mutations to choose from
    mutations = [i for i in 'ATCG' if i != virus[index]]

    # swap out the char at index with a random mutation
    return virus[:index] + random.choice(mutations) + virus[index+1:]

but my reproduce won't add the new viruses to the list if a virus reproduces ( based on reproductionProb), the new virus should be added to the already existing list of viruses,mutated or not,( mutate based on mutationProb ).

Each virus has an individual chance to reproduce

def reproduce(viruses, mutationProb, reproductionProb):
    for virus in viruses:
        if random.random() < reproductionProb:
            if random.random() < mutationProb:
                mutate(virus)
                viruses.append(virus)
            else:
                viruses.append(virus)
    return viruses

Anyone got any idea on why my function doesn't do that already? As I see it it append the mutated virus based on the mutationProb, else it appends it without mutating.




Aucun commentaire:

Enregistrer un commentaire