Python program to sort string in custom order

PythonServer Side ProgrammingProgramming

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
raja
Updated on 12-Oct-2021 08:51:07

Advertisements