Sunday, November 24, 2019

ginortS - Hacker Rank Solution

You are given a string .
 contains alphanumeric characters only.


Your task is to sort the string  in the following manner:
  • All sorted lowercase letters are ahead of uppercase letters.
  • All sorted uppercase letters are ahead of digits.
  • All sorted odd digits are ahead of sorted even digits.
Input Format
A single line of input contains the string .
Constraints
Output Format
Output the sorted string .
Sample Input
Sorting1234
Sample Output
ginortS1324

ginortS - Hacker Rank Solution

We can solve this by sorting   and   using key.

from __future__ import print_function

def func(x): 
    if x.isalpha():
        if x.isupper():
            return (ord(x)-ord('A'))
        else:
            return (ord(x)-ord('a'))-30
    else:
        if int(x) % 2 == 0:
            return 60+int(x)
        else:
            return 30+int(x)

s = raw_input()        
map(lambda x: print(x,end=''),(sorted(s,key = func)))
Without using key:
from __future__ import print_function

upper = []
lower = []
even = []
odd = []

def separator(a):
    
    if a.isalpha():
        if a.isupper():
            upper.append(a)
        else:
            lower.append(a)
    else:
        if int(a)%2 == 0:
            even.append(a)
        else:
            odd.append(a)
    return 
    
map(separator,raw_input())       

upper.sort()
lower.sort()
even.sort()
odd.sort()

t = lower+upper+odd+even
map(lambda x: print(x,end=''),t)


1 comment:

  1. s=input()
    l=[]
    m=[]
    n=[]
    k=[]

    a=sorted(s)
    for i in a:
    if i.islower():
    l.append(i)
    elif i.isupper():
    m.append(i)
    elif int(i)%2!=0:
    n.append(i)
    else:
    k.append(i)
    l=''.join(l)
    m=''.join(m)
    n=''.join(n)
    k=''.join(k)
    print(l+m+n+k)

    ReplyDelete

Powered by Blogger.