Python program to sort string in custom order


Suppose we have one alphanumeric string s. We have to sort it based on following condition

  • All sorted lowercase letters will be placed before uppercase letters.

  • All sorted uppercase letters will be placed before digits.

  • All sorted odd digits will be placed before sorted even digits.

So, if the input is like s = "HeLlo1234", then the output will be eloHL1324

To solve this, we will follow these steps −

  • Define a function f() . This will take c
  • code := 0
  • if c is in upper case, then
    • code := 10^3
  • otherwise when c is a digit, then
    • code := 10^6
  • if ASCII of c is even, then
    • code := 10^9
  • return code + ASCII of c
  • From the main method do the following
  • l := sorted list of s and order each character c in s by calling f() function
  • join each character in l and return

Example

Let us see the following implementation to get better understanding

def f(c):
   code = 0
   if c.isupper():
      code = 10 ** 3
   elif c.isdigit():
      code = 10 ** 6
      if ord(c) % 2 == 0:
         code = 10 ** 9
   return code + ord(c)

def solve(s):
   l = sorted(s, key=lambda c: f(c))
   return ''.join(l)

s = "HeLlo1234"
print(solve(s))

Input

"HeLlo1234"

Output

eloHL1324

Updated on: 12-Oct-2021

657 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements