Reputation: 23
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
Upvotes: 2
Views: 3035
Reputation: 2607
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
Upvotes: 4
Reputation: 14238
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
Upvotes: 0