HackerRank Solution: Python Find a string [3 Methods]


Hacker Rank Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Question: Find a String [Python Strings]

In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.

NOTE: String letters are case-sensitive.

Input Format

The first line of input contains the original string. The next line contains the substring.

Constraints

1<= len(string) <=200

Each character in the string is an ASCII character.

Output Format

Output the integer number indicating the total number of occurrences of the substring in the original string.

Sample Input

ABCDCDC
CDC

Sample Output

2

Concept

Some string processing examples, such as these, might be useful.
There are a couple of new concepts:
In Python, the length of a string is found by the function len(s), where s is the string.
To traverse through the length of a string, use a for loop:

for i in range(0, len(s)):
    print (s[i]

A range function is used to loop over some length:

range (0, 5)

Possible solutions to the problem

Now, we will discuss the possible solutions to the given problem. The following code is already given in the hacker rank:

def count_substring(string, sub_string):
    return

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

We have to write our code under the count_substring() method.

 

Solution-1: Using while loop'

Let us now solve the problem using the while loop.

def count_substring(string, sub_string):
    counting = 0
    while sub_string in string:
        a=string.find(sub_string)
        string=string[a+1:]
        counting += 1
    return counting

    
if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

The function count_substring() initializes a variable "counting" to 0 and enters a while loop that continues as long as the substring appears within the string. Within the while loop, the code uses the string method "find()" to locate the first occurrence of the substring within the string, assigns the index of this occurrence to the variable "a", then re-assigns the string to a slice that starts one character after the end of the substring. Finally, it increases the counting by 1. When the substring is no longer in the string, the function returns the final count of the substring's occurrences.

 

Solution-2: Using if statement

Now we will use the if statement inside the function to solve the problem:

c = 0
def count_substring(string, sub_string):
    global c  
    if(string.find(sub_string) != -1):
        c = c +1
        count_substring(string[string.find(sub_string)+1:],sub_string)
    return c
    
if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

This solution defines a function called "count_substring" that takes in two arguments: "string" and "sub_string", and a global variable "c" initialized to zero. The function first checks if the substring is present in the string using the string method "find()" and if present it increases the global variable 'c' by 1. It then calls the function recursively with the string starting from the next index of the substring. This process continues until the substring is not found in the string anymore. Finally, the function returns the final count of the substring's occurrences, stored in the global variable 'c'. This function utilizes recursion to achieve the count of substring in the main string.

 

Solution-3: Using for loop

Now we will use the for loop to solve the problem:

def count_substring(string, sub_string):
    return sum(string[i:].startswith(sub_string) for i in range(len(string)))

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

Similar to previous solutions, this solution defines a function called "count_substring" that takes in two arguments: "string" and "sub_string". It uses a list comprehension to generate a list of Boolean values representing whether each substring of the main string starting from index i is equal to the provided sub_string. The function then uses the built-in function "sum()" to count the number of True values in the list, which corresponds to the number of times the sub_string appears in the string. This code differs from the previous ones in that it utilizes Python's built-in string method "startswith()" and the "sum()" function to achieve the count of substring in the main string, instead of using loops or recursion. This version of the code is more concise and readable, and also relatively faster.

 

Summary

In this short article, we discussed how we can solve the Find a String question on hacker rank. We covered three different solutions and explained each of them.

 

Further reading

Question on Haker Rank: Find a String [Python Strings]

 

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!!

2 thoughts on “HackerRank Solution: Python Find a string [3 Methods]”

  1. Can anyone help me if the below solution is fair for an interview prospective: I am new for coding in python, so excuse any silly logic. Thank you.

    def count_substring(string, sub_string):
        
        n = 0
        iterations = (len(string) - len(sub_string) - 1)
        temp = []
        compare_lst = []
        count = 0
        
        while (n < iterations):
            temp = []
            for i in range(n, len(sub_string)+n ,1):
                temp.append(string[i])
                temp_str = ('').join(temp)
                
            compare_lst.append(temp_str)
            n += 1
        
        for i in range(0, len(compare_lst), 1):
            if (sub_string == compare_lst[i]) :
                count += 1
            
        return count
    Reply

Leave a Comment