0

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?

jbssm
  • 6,861
  • 13
  • 54
  • 81

3 Answers3

6

try

>>> chromo[gene1Pos], chromo[gene2Pos] = chromo[gene2Pos], chromo[gene1Pos]

So you just need to make sure you have the right genXPos

PaulMcG
  • 62,419
  • 16
  • 94
  • 130
louis.luo
  • 2,921
  • 4
  • 28
  • 46
  • 1
    See http://stackoverflow.com/questions/4554130/fastest-way-to-swap-elements-in-python-list for discussion of what this compiles to and why it's the fastest. – dkamins Dec 31 '11 at 02:23
  • Thank you. This is a bit prettier and as dkamins points out, faster. – jbssm Dec 31 '11 at 02:27
1

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]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
-1

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
dkamins
  • 21,450
  • 7
  • 55
  • 59
  • 2
    No, no, no! This is not Python you are thinking of! In Python, tuple unpacking and tuple assignment allows you to write: `a,b = b,a` Done! – PaulMcG Dec 31 '11 at 03:03
  • @PaulMcGuire Agreed. See my comment on your answer (which I upvoted) re performance (`a,b=b,a` is fastest). But swapping via temp is and always will be a classic micro-algorithm to keep in any programmer's toolbox. – dkamins Dec 31 '11 at 04:07