0

Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.

count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2

My Code

def count_code(str):
count=0
  for n in range(len(str)):
    if str[n:n+2]=='co' and str[n+3]=='e':
        count+=1
  return count

I know the right code (just adding len(str)-3 at line 3 will work) but I'm not able to understand why str[n:n+2] works without '-3' and str[n+3]

Can someone clear my doubt regarding this ?

Adhun Thalekkara
  • 713
  • 10
  • 23
Dragovic
  • 39
  • 6
  • There is a difference between how slices and single-item indexing work with indices that are out of range. `str[n+3:n+4]` would work here. – alani Jul 30 '20 at 09:50
  • See also https://stackoverflow.com/questions/9490058/why-does-substring-slicing-with-index-out-of-range-work – alani Jul 30 '20 at 09:53

3 Answers3

1

Say our str was "abcde".

If you didn't have the -3 in the len(str), then we would have an index of n going from 0,1,2,3,4.

str[n+3] with n being 4 would ask python to find the 7th letter of "abcde", and voila, an indexerror.

JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24
  • 2
    I think the question is about the fact that the slice doesn't give an error *despite* being out of range, whereas the simple indexing does - contrasting the `str[n:n+2]` and the `str[n+3]` – alani Jul 30 '20 at 09:56
  • yes you're right, this was also my doubt but couldn't explain it this clearly – Dragovic Jul 30 '20 at 10:04
1

It is because the for loop will loop through all the string text so that when n is representing the last word. n+1 and n+2does not exist. Which it will tells you that the string index is out of range.

For example: 'aaacodebbb' the index of the last word is 9. So that when the for loop goes to the last word, n=9. But n+1=10 and n+2=11 index does not exist in your word. So that index 10 and 11 is out of range

Oscar916
  • 119
  • 1
  • 3
0

loop for is an easy way to do that.

def count_code(str):
  count = 0
  for i in range(len(str)-3): 
# -3 is because when i reach the last word, i+1 and i+2
# will be not existing. that give you out of range error.  
      if str[i:i+2] == 'co' and str[i+3] == 'e':
      count +=1
  return count