HackerRank Solution: ginortS in Python [5 Methods]


Written by - Bashir Alam
Reviewed by - Deepak Prasad

Question: ginortS - Hacker Rank (Python)

You are given a string S.
S 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 S.

Constraint:
0 < len(S) < 1000

Output Format:

Output the sorted string S.

Sample Input:

Sorting1234

Sample Output:

ginortS1324

 

Possible Solutions

As you can see, we have to sort a string based on some conditions. Now, we will use multiple ways to sort the given string based on the condition specified in the question.

  • Using Lambda function
  • Solving in one line
  • Using if-else statements
  • Without using sorted() function
  • Using user-defined function

Let us start with solving the question.

 

Solution-1: Using the Lambda function

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. We will now use the lambda function to sort the string based on the conditions given in the question.

# taking the input from user
s = input()

# using the lamnda function to filter and then sort
s = sorted(s,key = lambda x:(x.isdigit() and int(x)%2==0, x.isdigit(),x.isupper(),x.islower(),x))

# printing the sorted string
print(*(s),sep = '')

Sample input:

Sorting1234

Output:

ginortS1324

As you can see, the program has successfully sorted the input string. Let us now give any random string to see, if it will be sorted based on the conditions or not.

Input:

Bashir127alam

Output:

aaahilmrsB172

As you can see, the string has been sorted as per required.

 

Solution-2: Solving the question in one line

Another modification we can do in the solution is to write all conditions in one line. It is the beauty of Python that we can write less code to get the same results. Let us now write the solution in only one line.


# Taking input ,sorting and printing in one line
print(*sorted(input(), key=lambda c: (c.isdigit() - c.islower(), c in '02468', c)), sep='')

Input:

Sorting1234

Output:

ginortS1324

As you can see, we get the desired result by just writing one line of code.

 

Solution-3: Using If-else statements

As we know, there are some conditions given in the question for sorting the string. So, we can use if-else statements to for these conditions and sort the string accordingly.

# creating lists
l = []
u = []
o = []
e = []

# using for loop in sorted string from user
for i in sorted(input()):
    
    # checking is the character is alphabet
    if i.isalpha():
        
        # Checking is the alphabet is upper letter or not
        x = u if i.isupper() else l
    
    # if the character is not alphabet, this code will execute
    else:
        
        # assigning accordingly
        x = o if int(i)%2 else e
        
    # apending and joining all characters.
    x.append(i)
print("".join(l+u+o+e))

Input:

Sorting1234

Output:

ginortS1324

As you can see, we get the desired output.

 

Solution-4: Without using sorted()method

Now, we will sort the given string based on the conditions, without using the sorted() method. For that we first have to import the ascii_lowercase and ascii_uppercase. Let's start the coding.

# importing the module
from string import ascii_lowercase, ascii_uppercase 

# sorting accordingly
sortkey = ascii_lowercase + ascii_uppercase + "1357902468"

# taking input from user
x = input()

# printing sorted string
print(*map(lambda y: y * x.count(y), sortkey), sep='')

Input:

Sorting1234

Output:

ginortS1324

As you can see, we were able to sort based on the given conditions without using sorted() method.

 

Solution-5: Using user-defined function

A user-defined function is a function provided by the user of a program or environment, in a context where the usual assumption is that functions are built into the program or environment. We will now create a user-defined function that will sort the given string and will print the sorted one based on the conditions given in the question.

# defining the string
def sorting(s):
    
    # using the lamnda function to filter and then sort
    s = sorted(s,key = lambda x:(x.isdigit() and int(x)%2==0, x.isdigit(),x.isupper(),x.islower(),x))

    # printing the sorted string
    print(*(s),sep = '')
    
# calling the function with input string
sorting(input())

Input:

Sorting1234

Output:

ginortS1324

As you can see, we get the desired output.

 

Summary

In this short article, we solved the ginortS question on Hacker Rank by providing multiple solutions. We have use lamda and user-defined functions to solve the question.

 

References

Python lambda function
Question on Hacker Rank: Athlete Sort in Python

 

Views: 19

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment