useruseruser
useruseruser

Reputation: 49

How do I fix this code to recognise overlapping strings?

entrada = str(input().lower())

replace = "mem".lower()
find = entrada.lower()
count = 0
while (entrada.find(replace) != -1):
   entrada = entrada.replace(replace, "", 1)
   count +=1

print(count) 

No count,list or lambda can be used. I'm suposed to make a program that receives a lower string from the user then finds, counts and print the number of times a substring appeared. But I'm having problems with overlapping strings.

example: string is memem, the expected exit is 2

Upvotes: 1

Views: 84

Answers (2)

Shashank
Shashank

Reputation: 13869

One way to do this is to use the second argument of str.find which indicates an optional index to start searching for the substring within a string.

From the docs:

str.find(sub[, start[, end]])¶ Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

So if we keep track of the last_index found in a variable, we can simply start the search for the substring again in the next possible index. Expressed in code, this is the expression last_index + 1. If last_index is ever -1, we stop searching for the substring and output our count:

mystr = 'memem'
mysubstr = 'mem'
count = 0
last_index = -1
while True:
    last_index = mystr.find(mysubstr, last_index + 1)
    if last_index == -1:
        break
    count += 1

print(count)

Upvotes: 3

pppery
pppery

Reputation: 3814

You could use

i = 0
while True:
    i = entrada.find(replace, i) + 1
    if i:
         count += 1
    else:
        break

This will then find replace in entrada, increment the count, find replace in entrada[i+1:] where i is the start of the previous match, increment the count, and repeat forever.

Upvotes: 0

Related Questions