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
    • swap nums[i] and nums[i + 2]
  • if i + 3
  • 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 

    Input

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

    Output

    [3, 4, 8, 5, 3, 6, 8, 9, 4, 7]
    Updated on: 2021-10-14T11:03:24+05:30

    535 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements