2

I am attempting to write a code snippet that requests from the user to enter a string s and then a substring ss. The program will then have to count the number of occurrences of ss in s. For example if the user enters s = ‘azcbobobegghakl’ and ss = ‘bob’, then the program should print: Number of times bob occurs is: 2.

Here is my code so far :

def count(s,ss):
    Occurrence = 0
    if ss in s :
        for ss in s :
            Occurrence += 1
    return Occurrence 

#Main program : 
    
s = str(input("Choose a string: "))
    
ss = str(input("Choose a substring:")) 
    
print ("Number of times " + str(ss) + " occurs is : " + str(count(s,ss)) ) 

My desired output would be this:

Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 2

But instead I get this :

Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 8

So can someone please help me modify this code to deliver the desire output? Thanks in advance

2 Answers 2

4

you can use count

print("hellohel".count("hel"))
2

If you want to count overlapping occurrences... maybe this can help

def countOverlapping(string, item):
    count = 0
    for i in range(0,len(string)):
        if item in string[i:len(item)+i]:
            count += 1
    return count

print(countOverlapping("ehehe", "ehe"))

output should be...

2

How does that work?

as @SomeDude mentioned it uses what he calls a sliding window approach

we take the length of the substring and check if its in that "window" of the string each iteration:

is ehe in [ehe]he? yes, count += 1
is ehe in e[heh]e? no, pass
is ehe in eh[ehe]? yes, count += 1
Sign up to request clarification or add additional context in comments.

2 Comments

Understood. Thanks Ironkey.
No problem, if you liked a particular answer/explanation you can click the green checkmark to accept it for people with this question in the future, thanks for asking!
0

You need to go for a sliding window approach to get count of substrings in a string.

example:

string : "ehehehe"

substring : "ehe"

start with first 3 ( because length of substring is 3 ) letters "ehe"- is it the substring we are looking for? - yes.

now leave the first letter "e" and combine letters "he" with the next letter "h" to form "heh" is it the substring we are looking for? - no

now leave the first letter "h" and combine letters "eh" with the next letter "e" to form "ehe" is it the substring we are looking for ? yes

do it till the end of the string and count number of "yes"s

1 Comment

Thanks for the help dude.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.