Suppose we have a list of numbers called nums, we will exchange each consecutive even indexes with each other, and also exchange each consecutive odd index with each other.
So, if the input is like [1,2,3,4,5,6,7,8,9], then the output will be [3, 4, 1, 2, 7, 8, 5, 6, 9]
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): length = len(nums) for i in range(0,length,4): if(i+2<length): nums[i], nums[i+2] = nums[i+2], nums[i] if(i+3<length): nums[i+1], nums[i+3] = nums[i+3], nums[i+1] return nums ob = Solution() nums = [1,2,3,4,5,6,7,8,9] print(ob.solve(nums))
[3, 4, 1, 2, 7, 8, 5, 6, 9]