Output gives me correct answer sometimes, but incorrect answers as well(Usaco 2021 december bronze problem)

For the december bronze problem Lonely Photo, I have all of my code and analysis on this link here.
However I have issue which I cant explain. When I input sequences like HGHGH, the output gives me the correct value 3. However when I input sequences like HHHHG or GGHH, it gives me the wrong values of 0 each time.
Would you know why this is happening and how can I fix this?

You have a couple of misunderstandings of how Python works.
The first is that a for loop does not reach the value given, so for example,

for i in range(5):



and would never reach 5.

The second issue is that when indexing(indicing?) a string or list, it does not include the second value included. So for example,

lst = [1, 2, 3, 4, 5, 6, 7]


[3, 4, 5]

For a string, it would look like

s = "abcdefg"

would output


Hopefully this helps!

I took a look at your code, and this is happening because python’s (and other languages) range function does not include the end value. For example, calling for i in range (0, 5) will use values i 0 to 4. If you want end as your last value, use range(start, end+1). So, with this in mind, there are 4 places in your code that you would want to fix: both for loops (lines 35 & 36 on your codeskulptor file) & both sublists (lines 37 & 38). This should make it pass all cases.

Let me know if you have any more questions.

I got it to work. Thank you so much…

1 Like