Hackerrank Solution: Compress the string Python


Hacker Rank Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Question: Compress the string - Hacker Rank (Python)

In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools. You are given a string  S. Suppose a character C occurs consecutively X times in the string. Replace these consecutive occurrences of the character C with (X, C) in the string.

For a better understanding of the problem, check the explanation.

Input Format

A single line of input consisting of the string S.

Output Format
A single line of output consisting of the modified string.

Constraints

All the characters of S denotes integers between 0  and 9.

1 <= | S | <= 10^4

Sample input:

1222311

Sample output:

(1, 1) (3, 2) (1, 3) (2, 1)

First, character 1 occurs only once. It is replaced by (1, 1). Then the 2 character occurs three times, and it is replaced by (3, 2)  and so on.

Also, note the single space within each compression and between the compressions.

 

Possible solutions

In this question, we will use the function groupby() of itertools module. For those of you who are not familiar with itertools, It is a module in python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module incorporates functions that utilize computational resources efficiently.

The groupby() method of itertools goes through an iterable and groups values based on a particular key. Then it returns an iterator(stream of tuples). The first value of a tuple consists of keys, on which the items of iterable were grouped. And that is exactly what is being asked in the question.

Here we will try to solve the question using multiple ways, but we will stick to using the groupby() function as it is required in the question.

  1. Using Groupby method
  2. Using Python function with Groupby method
  3. Using __name__ variable

compress-string

 

Solution-1: Using Groupby method

As it is given in the question to use groupby method from itertools, we will first import the groupby method from the itertools and then will use it to find the desired output.

# importing the groupby method
from itertools import groupby

# using for loop to iterate through the string
for k, c in groupby(input()):
        
    #printing the output
    print("(%d, %d)" % (len(list(c)), int(k)), end=' ')

As you can see, the above code takes the string from the user.

Input:

1222311

Output:

(2, 1) (3, 2) (2, 3)

In a similar way, you can provide any kind of string and it will give the desired output.

 

Solution-2: Using a Python Function with groupby

We will now create a Python function that will print out the required output. But before it, we have to import the groupby() from the itertools.

# importing the groupby method
from itertools import groupby

# creading a function
def main(string):
    
    # using for loop to iterate through the string
    for k, c in groupby(string):
        
        #printing the output
        print("(%d, %d)" % (len(list(c)), int(k)), end=' ')
        
# calling the function
main(input())

Input:

1222311

Output:

(1, 1) (3, 2) (1, 3) (2, 1)

As you can see, we get the desired output result.

 

Solution-3: Using If __name__

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.

In this section, we will use __name__ =='main', which runs blocks of code only when our Python script is being executed directly from a user. This is powerful as it allows our code to have different behavior when it's being executed as a program instead of being imported as a module.

# importing the required module
from itertools import groupby

# using if __name__ variable
if __name__ == "__main__":
    
    # using for loop to iterate through the string
    for k, c in groupby(input()):

        #printing the output
        print("(%d, %d)" % (len(list(c)), int(k)), end=' ')

Input:

1222311

Output:

(1, 1) (3, 2) (1, 3) (2, 1)

As you can see, we again get the desired output.

 

Summary

In this short article, we solved the string compressed question from the Hacker Rank. We solved the challenge using multiple ways and you can pick any of these solutions.

 

References

Python itertools
Question on Hacker Rank

 

Bashir Alam

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 Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

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