Program to find array by swapping consecutive index pairs in Python


Suppose we have a list of numbers called nums, we have to return the list by swapping each consecutive even indexes with each other, and swapping each consecutive odd indexes with each other.

So, if the input is like nums = [8,5,3,4,8,9,3,6,4,7], then the output will be [3, 4, 8, 5, 3, 6, 8, 9, 4, 7]

To solve this, we will follow these steps −

  • for i in range 0 to size of nums - 2, increase by 4, do
    • if i + 2 < size of nums, then
      • swap nums[i] and nums[i + 2]
    • if i + 3 < size of nums, then
      • swap nums[i + 1] and nums[i + 3]
  • return nums

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   for i in range(0, len(nums) - 2, 4):
      if i + 2 < len(nums):
         nums[i], nums[i + 2] = nums[i + 2], nums[i]
      if i + 3 < len(nums):
         nums[i + 1], nums[i + 3] = nums[i + 3], nums[i + 1]

   return nums

nums = [8,5,3,4,8,9,3,6,4,7]
print(solve(nums))

Input

[8,5,3,4,8,9,3,6,4,7]

Output

[3, 4, 8, 5, 3, 6, 8, 9, 4, 7]

Updated on: 14-Oct-2021

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements