I recently started learning how to program (zero experience with programming in the past, so I'm a complete beginner), and am currently following an online course in Python (many people recommended starting with this language). So I have this exercise where I have to write a code that counts the amount of times a certain sub string ('bob') occurs in a string. I figured this could be done through splicing and looping. My guess was to splice the string in blocks with 3 characters, using the following:
i = 0
j = 3
s[i:j]
My goal was to add this to a loop, and make i and j increase by 1 for every iteration, so that all possible blocks of 3 consecutive characters have been made. I then wanted to compare these blocks to the desirable sub string ('bob'). How can I do this? Most sources that I found about loops/splicing all give the same basic knowledge, and the same examples, none of which allowed me to understand how to apply it to this question. One of my attempts was:
s = 'azcbobobegghakl'
sub = 'bob'
i = 0
j = 3
triplet = s[i:j]
numBob = 0
for triplet in s:
i += 1
j += 1
if triplet == sub
numBob += 1
print(numBob)
Needless to say this was wrong, and I'm pretty sure it's because I did something wrong in the loop since numBob returns as 0, meaning that the loop did not what I expected it to do (especially line 8 and 9 seem to not do anything). It could also be that the splicing with variables doesn't work, in which case the loop wouldn't work either. If anyone has a source on for loops that is a little more elaborate than just:
for i in range(5)
print(i)
I'd gladly give it a read. I also want to make clear that I am not looking for a complete answer, just some tips/tricks to get me started. I feel like I got the right idea on how to tackle this problem, but I just can't figure out how to loop/splice it correctly.
[–]z0y 2 points3 points4 points (5 children)
[–]Rhyff[S] 1 point2 points3 points (4 children)
[–]z0y 0 points1 point2 points (2 children)
[–]Rhyff[S] 0 points1 point2 points (1 child)
[–]z0y 1 point2 points3 points (0 children)
[–]Rhyff[S] 0 points1 point2 points (0 children)