Reputation: 7151
Is there any easy way to exchange the position of 2 elements - or better yet, n elements - in an array?
I came up with some code, but it looks quite ugly and the performance should be a bit bad:
chromo = [[1,2], [3,4], [5,6]]
gene1Pos = random.randrange(0, len(chromo)-1, 1)
gene2Pos = random.randrange(0, len(chromo)-1, 1)
tmpGene1 = chromo[gene1Pos]
tmpGene2 = chromo[gene2Pos]
chromo[gene1Pos] = tmpGene2
chromo[gene2Pos] = tmpGene1
This should work, but well, it's not nice. The better way would be a routine like random.shuffle but that instead of mixing everything would mix just a number n of elements. Do you have any idea?
Upvotes: 0
Views: 450
Reputation: 2971
try
>>> chromo[gene1Pos], chromo[gene2Pos] = chromo[gene2Pos], chromo[gene1Pos]
So you just need to make sure you have the right genXPos
Upvotes: 6
Reputation: 21918
There's nothing wrong with what you're doing. You can simplify it by removing one of the temp variables though. To swap a
and b
, all you need is this:
tmp = a
a = b
b = tmp
Upvotes: -1
Reputation: 798546
Just combine the normal mechanism for swapping variables in Python with slicing/slice assignment.
>>> a = [1, 2, 3, 4, 5]
>>> a[2:3], a[4:5] = a[4:5], a[2:3]
>>> a
[1, 2, 5, 4, 3]
Upvotes: 1