Swap Consecutive Even Elements in Python


Suppose we have a list of numbers called nums, we have to exchange every consecutive even integer with each other.

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

To solve this, we will follow these steps −

  • temp := null
  • for i in range 0 to size of nums, do
    • if nums[i] mod 2 is same as 0, then
      • if temp is not null, then
        • exchange nums[i], nums[temp]
        • temp := null
      • otherwise,
        • temp := i
  • return nums

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      temp = None
      for i in range(len(nums)):
         if nums[i] % 2 == 0:
            if temp is not None:
               nums[i], nums[temp] = nums[temp], nums[i]
               temp = None
            else:
               temp = i
      return nums
ob = Solution()
print(ob.solve([4, 5, 6, 8, 10]))

Input

[4, 5, 6, 8, 10]

Output

[6, 5, 4, 10, 8]

Updated on: 22-Sep-2020

421 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements