AllenDowney / ThinkPython2

LaTeX source and supporting code for Think Python, 2nd edition, by Allen Downey.
Other
2.49k stars 1.65k forks source link

cartalk1, why using i=i+1-2*count? #78

Open Naolador opened 3 years ago

Naolador commented 3 years ago

I just don't understand why we use "i = i + 1 - 2*count" to reset the pointer in line 31 if two nearby characters doesn't match. I replaced the line with "i = i + 1" and got the same result.

jerryu commented 3 years ago

I am also curious, so I added some debugging code to output

The i=i+1 proposed by Naolador seems to have the desirable/expected flow.

Allowing overlapped counting might require walking the pointer back, depending on the flow. To illustrate, I made up a word, 'booookmaker'. Both solutions don't allow overlapping, whereas the second 'o' forms one double with 'o' before and another double with 'o' after.

 reset  booookmaker 0   0   1   0        reset  booookmaker 0   0   1   0
 double  ooookmaker 1   0   3   1        double  ooookmaker 1   0   3   1
 double    ookmaker 3   1   5   2        double    ookmaker 3   1   5   2
 reset       kmaker 5   2   2   0         |  reset       kmaker 5   2   6   0
 double   oookmaker 2   0   4   1         <
 reset      okmaker 4   1   3   0         <
 double    ookmaker 3   0   5   1         <
 reset       kmaker 5   1   4   0         <
 reset      okmaker 4   0   5   0         <
 reset       kmaker 5   0   6   0         <
 reset        maker 6   0   7   0        reset        maker 6   0   7   0
 reset         aker 7   0   8   0        reset         aker 7   0   8   0
 reset          ker 8   0   9   0        reset          ker 8   0   9   0
 reset           er 9   0   10  0        reset           er 9   0   10  0