Problem Set 3 Problem 4 bug question:
See my code here: http://pastebin.com/hd5jHVVr
This code fails the test case test subStringMatchExactlyOneSub(target1,key10) because it does not return the last location 20 when subStringMatchOneSub(target1,key10) is called.
I corrected this by changing the for loop on line 53 to the following:
for i in range(0,len(target)+1):
Can anyone explain why the +1 is necessary when len(target) is equal to the length of the string and should iterate through all characters?
MIT 6.00 Intro Computer Science (OCW)
Stacey Warren - Expert brainly.com
Hey! We 've verified this expert answer for you, click below to unlock the details :)
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
I got my questions answered at brainly.com in under 10 minutes. Go to brainly.com now for free help!
So, good question and, thankfully, the answer is just that this is a strange syntactical idiosyncrasy with Python... When you specify a range in Python, it starts at the beginning - in this case 0 - and then goes all the way **up-to-but-not-including** the final number. That's it. So, for ex., if you were searching through the integers 0 and 4,
for i in range(0, 4)
i=0, i=1, i=2 and i=3,
for i in range(0,5)
would also do i=4, but **not** i=5.
Mathematically, for i in range(0,4) searches the set of integers [0,4) and for i in range(0,5) searches the set of integers [0,4] (which is [0,5) too...)
AlexanderR, I tried your code. I guess this '+1' just happens to solve it. My solution works just fine and it's a little bit more efficient.
@swdalb So, the bug was coming from the range() function. Thanks, I was focusing in on the len() function. Lesson learned, calling the function range(0,len(string)) for any reason can cause some bugs because the loop will iterate one cycle to few.
@oogs Agreed, more efficient than pure enumeration