0

I have a list of elements from 1 to n, (range(1, n + 1))

How should I swap odd greater elements with the even elements?

for example, if I have a list with elements [1,2,3] the desired output will be [1,3,2] because odd 3 is greater than even 2 .

example 2:

if list = [1,2,3,4,5]

the desired output will be

[1,3,2,5,4] 

Here 2 will be swapped with 3 and 4 will be swapped with 5 but not with 3 because 3 is smaller than 4.

Minion3665
  • 879
  • 11
  • 25
Akash nitter
  • 111
  • 7

2 Answers2

4

A simple for loop, to modify the list in place:

l = list(range(1,10))

for i, n in enumerate(l):
    if i % 2 != 0 and i < len(l) - 1:
        l[i] = l[i+1]
        l[i+1] = n

At every odd index, the element swaps places with its successor.

Wups
  • 2,489
  • 1
  • 6
  • 17
3

You can use list slicing of even/odd numnbers, zip them and create a solution list from that:

def interleave(n):
    k = list(range(1, n))

    k[:] = k[:1]+[y for x in zip(k[2::2], k[1::2]) 
            for y in x] + (k[-1:] if len(k)%2 == 0 else [])

    return k

print(interleave(20))
print(interleave(21))

Output:

[1, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 17, 16, 19, 18]
[1, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 17, 16, 19, 18, 20]

Explanation:

  • you keep the 1
  • you get all odd ones from position 2 to end, stepsize 2
  • you get all even ones from position 1 to end, stepsize 2
  • you interleave them using zip
  • you recombine them using a nested list comprehension of [x for y in sequence for y in x] where y are the tuples resulting by zipping two slices
  • you compensate for even/odd sized input lists

Further reading:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    To be consistent with OP you want `k = list(range(1, n+1))` to get list to be 1..n inclusive. – DarrylG Oct 04 '20 at 10:12
  • @DarrylG the OP never showed how he creates his list - but if wanted your suggestion would fix my method to do `n` inclusively - I chose exclusively. – Patrick Artner Oct 04 '20 at 10:23
  • 1
    @PatrickArtner--True, that's why I upvoted your answer with my suggestion. – DarrylG Oct 04 '20 at 10:26