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 ?

2
  • 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. Commented Jul 30, 2020 at 9:50
  • See also stackoverflow.com/questions/9490058/… Commented Jul 30, 2020 at 9:53

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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]
yes you're right, this was also my doubt but couldn't explain it this clearly
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.