I am kind of new in this python. I am trying to learn how to modify functions. In this case, I found the code below online. I want to learn how to make it work only with probability = 0.9. That is to say, if I have two binary strings like ('1001001010001','100000001100'), I want to swap their halves only with probability 0.9.
That will be the code with probability 0.9 will cut the original strings into two halves like ('1 | 2' ,'3 | 4') and swap them like [1 | 4 , 3 | 2].
This is the code I have so far:
def crossover(i1, i2):
assert len(i1) == len(i2)
n = len(i1); split_index = random.randint(0+1, n-1)
return '{}{}'.format(i1[:split_index], i2[split_index:]), \
'{}{}'.format(i1[split_index:], i2[:split_index])
## in: ('00010', '11000') out: ('00|000', '010|11') with split at 2.
This is what I thought. It doesn't look elegant at all, although it works. Any help to learn how others would do it? Thanks a lot for all your help!!
def crossover(i1, i2, threshold):
assert len(i1) == len(i2)
n = len(i1); split_index = random.randint(0+1, n-1)
return '{}{}'.format(i1[:split_index], i2[split_index:]), \
'{}{}'.format(i1[split_index:], i2[:split_index]) \
if random.uniform(0, 1) <= threshold \
else '{}{}'.format(i1[:split_index], i1[split_index:]), \
'{}{}'.format(i2[split_index:], i2[:split_index]) \
## in: ('00010', '11000') out: ('00|000', '010|11') with split at 2.