Reputation: 111
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.
Upvotes: 0
Views: 191
Reputation: 51643
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:
[x for y in sequence for y in x]
where y
are the tuples resulting by zipping two slicesFurther reading:
Upvotes: 3
Reputation: 2569
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.
Upvotes: 4