1

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.

1 Answers1

1

Your logic is fine, but why are you using format to do simple concatenation? Also, in the non-swap case, why do you split each string and then restore its original state?

if random.uniform(0, 1) <= threshold:
    return (i1[:split_index] + i2[split_index:],
            i1[split_index:] + i2[:split_index])
else:
    return (i1, i2)
Prune
  • 76,765
  • 14
  • 60
  • 81
  • Regarding the question about the format is because I am learning by myself, and I am trying to learn with code I find and I work with it changing what I want for my own thesis. So do not know well what ```format``` does. Regarding the second question, I do it that way so that I make the function to cross the strings only the 90% of the times. I do not know how to execute the probability in a different way. – Jorge Martinez Mar 08 '21 at 06:47
  • I strongly recommend that you follow a simple curriculum, rather than using "code I find". There are many free courses and comparable materials on line. – Prune Mar 08 '21 at 06:58