-2

I have to write a code substrn, which takes string arguments sup and sub, and returns the integer count of the (possibly overlapping) number of times sub can be found in sup.

I wrote this code

def substrn(sup,sub):
   if sub in sup:
      x = 0
      for i in sup:
         if sub in sup[sup.index(i):(int(len(sub))+int(sup.index(i)))]:
            x = x +1 
      return x 
   else:
      return 0

print(substrn("wooloomooloo", "oo"))
print(substrn("wablabmablab", "ab"))

Can anyone help me understand what went wrong with my code and how I can change it? My first print statement produced 8 but my second print statement produced 4, they should be the same.

1 Answers1

-1

Here try this instead:

def substrn(sup,sub):
       # if sub in sup: # this is redundant since you are already checking 
      x = 0
      for i in range(len(sup)):
         if sub == sup[i:int(len(sub))+i]: 
         # try not to use a in b as this indicates partial search
         # so to make your logic more explicit you use a == b 
            sup[i:int(len(sub))+i]
            x = x +1 
      return x 


print(substrn("wooloomooloo", "oo")) # prints 4
print(substrn("wablabmablab", "ab")) # prints 4

The main problem in your initial code is this portion for i in sup: and sup.index(i).

for i in sup: iterates through each letter in sup and sup.index(i) will only find the first occurrence of the index of i in sup. It does not care about where i comes from, but only what i is.

If you actually printed out sup.index(i), you'll find that sup.index(i) will always be 1 for each loop, and hence when u execute substrn("wooloomooloo", "oo") it will always capture the first oo. Since you have 8 os, your substrn("wooloomooloo", "oo") will return 8

I hope this helps :)

chowsai
  • 565
  • 3
  • 15