Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find a String Hackerrank

Input:ABCDCDC
CDC
Output:2

def count_substring(string, sub_string):
        for i in range(0,len(string)):
            ans=string.count(sub_string)
            return ans

I am getting 1 as output how can I get 2 as output and read the full string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From every index look forward for next n characters if they match, n being the size of substring

def count_substring(string, sub_string):
    n = len(sub_string)
    ans = 0
    for i in range(0,len(string)):
        if(i+n > len(string)):#out of range problem
            break
        ans+=string.count(sub_string,i,i+n)
    return ans
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading