Danny W
Danny W

Reputation: 473

How do you swap integers in a list when those integers may repeat

My list contains random integers in no order. I want to swap elements while keeping the order of the list intact.

ran=[1,1,2,1]

And I want to swap say 1 and 2:

swap(ran,1,2)
output:
2212

or

ran=[3,3,1,2]
swap(ran,1,3)
output:
1132

I tried a swap function, but I know my iteration logic isn't very good.

def swap(c,x,y):

arr=[]

for i, v in enumerate(c):
        if v==x or v==y:
            for j,v2 in enumerate(c):
                if v2==y or v2==x:
                    arr[i], arr[j] = arr[j], arr[i]

This just changes one of the values.

The problem is not knowing which index has been changed already.

Upvotes: 0

Views: 97

Answers (3)

Miles C.
Miles C.

Reputation: 111

I think you could use something like this:

def swap(lst,x,y):
    ret = lst
    for e in range(0,length(lst)):
        if x == lst[e]:
            ret[e] = y
        if y == lst[e]:
            ret[e] = x
    return ret

Upvotes: 0

ggorlen
ggorlen

Reputation: 56965

Use a dict to encode the swapping logic and index into it with get(e, e). Any non-swappable elements that aren't in the dict will be left alone.

>>> def swap(lst, x, y):
...     swaps = {x: y, y: x}
...     return [swaps.get(e, e) for e in lst]
...
>>> swap([1, 1, 2, 1], 1, 2)
[2, 2, 1, 2]

You can generalize this by letting the caller pass in a dictionary to specify the swaps. Here's a closely related question.

Upvotes: 3

cschatz
cschatz

Reputation: 258

The examples you gave suggest the process you want isn't really a "swap" of individual elements as such, but more like a bi-directional "search and replace". If that's what's needed, a much simpler loop would work:

def swap(c, x, y):
  for i, v in enumerate(c):
    if v == x:
      c[i] = y
    elif v == y:
      c[i] = x

Upvotes: 4

Related Questions