Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
string_2, cat,dog
#1
count_cat = 0
  count_dog = 0
  for i in range(len(str)-2):
    if str[i:i+3] == 'dog':
      count_dog += 1
    if str[i:i+3] == 'cat':
      count_cat += 1
   
  return count_cat == count_dog
Can someone explain the purpose of the -2 in the for loop?
Reply
#2
You need to put your code in code blocks. The text editor here has a button that is the python symbol that will do that for you.

Now onto your question:
range(len(str)-2)
This is the code that's important to understanding your question.
This range produces the indices of all the letters in the string called str, except the last two. The minus two is what prevents the last two characters from being viewed by the for loop
The reason that this is done is shown here:
if str[i:i+3] == 'dog':
str[i:i+3]
is a slice of a string. This means that we are taking all the characters starting at index and ending just before index + 3. In other words the current character plus the next two. If we use this to search the entire string then we must stop the current character 2 characters before the end of the string or will run over the end of the string with our search.
Reply
#3
It's not good idea to use str as name.

>>> str(42)
'42'
>>> str = 'oh my god'
>>> str(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
Yes, str is reserved in python. I clipped the code from Gregor Ulm's website.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020