Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

![Mutation](http://i.imgur.com/HngmxNN.gif)

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.

A mutation is the change from `0` to `1` or from `1` to `0`.

***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*

# See other katas from this series

  - [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
  - **Genetic Algorithm Series - #2 Mutation**
  - [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
  - [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
  - [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)

Difficulty: introductory

Starter code:

def mutate(chromosome, p):
	

Solutions:
from random import random
def mutate(chromosome, p):
    res = ''
    for s in chromosome:
        res += str(1 - int(s)) if random() < p else s
    return res


from random import random


def mutate(chromosome, p):
    return ''.join((a, '01'[a == '0'])[random() <= p] for a in chromosome)


from random import random
def mutate(ch, p):
    return ''.join([str(1-int(i)) if random()<=p else i for i in ch])

from random import random

def mutate(chromosome, p):
    
    mutation = lambda x: '1' if x == '0' else '0'
    return ''.join([mutation(c) if random() < p else c for c in chromosome])

from random import *

def mutate(chromosome, p):
    def mutate(gene): return '1' if gene=='0' else '0'
    return "".join([(mutate(x) if random() <= p else x) for x in chromosome])


from random import random

def mutate(chromosome, p):
    return ''.join("01"[c=='0'] if random() <= p else c for c in chromosome)

import random
def mutate(chromosome, p):
    return ''.join(d if random.random() >= p else str(int(not int(d))) for d in chromosome)

import random
def mutate(chromosome, p):
    return ''.join([x if random.random() > p else '10'[int(x)] for x in chromosome])

import random
import string

tbl = string.maketrans('01', '10')


def mutate(chromosome, p):
    return ''.join(
        c.translate(tbl) if random.random() <= p else c
        for c in chromosome
    )

from random import random
def mutate(chromosome, p):
    opp = {'0':'1','1':'0'}
    return ''.join(opp[x] if random() < p else x for x in chromosome)