Program to sort all even and odd numbers in increasing and decreasing order respectively in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we have to sort the array by maintaining following criteria

  • Even numbers are sorted in ascending order
  • Odd numbers are sorted in descending order
  • The relative positions of the even and odd numbers should not be changed.

So, if the input is like [9, 14, 12, 91, -4, 5], then the output will be [91, -4, 12, 9, 14, 5]

To solve this, we will follow these steps −

  • evens := list of even terms in nums array
  • odds := list of odd terms in nums array
  • sort the list evens
  • even_i := 0, odd_i := 0
  • for index in range 0 to size of nums, do
    • if nums[index] mod 2 is same as 0, then
      • nums[index] := evens[even_i]
      • even_i := even_i + 1
    • otherwise,
      • nums[index] := odds[odd_i]
      • odd_i := odd_i + 1
  • return nums

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      evens = [num for num in nums if num % 2 == 0]
      odds = [num for num in nums if num % 2 != 0]
      evens.sort()
      odds.sort(reverse=True)
      even_i = 0
      odd_i = 0
      for index in range(len(nums)):
         if nums[index] % 2 == 0:
            nums[index] = evens[even_i]
            even_i += 1
         else:
            nums[index] = odds[odd_i]
            odd_i += 1
      return nums
ob = Solution()
print(ob.solve([9, 14, 12, 91, -4, 5]))

Input

[9, 14, 12, 91, -4, 5]

Output

[91, -4, 12, 9, 14, 5]
raja
Published on 06-Oct-2020 06:37:08
Advertisements