python - 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 used. i'm suposed make program receives lower string user finds, counts , print number of times substring appeared. i'm having problems overlapping strings.

example: string memem, expected exit 2

one way use second argument of str.find indicates optional index start searching substring within string.

from docs:

str.find(sub[, start[, end]])¶ return lowest index in string substring sub found, such sub contained in slice s[start:end]. optional arguments start , end interpreted in slice notation. return -1 if sub not found.

so if keep track of last_index found in variable, can start search substring again in next possible index. expressed in code, expression last_index + 1. if last_index ever -1, stop searching substring , 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) 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -