top of page
  • Writer's pictureMaulik Chopra

Python tricky question from MITx 6.00.1x | Strings

BOB (medium difficulty)

(PSET-1, Question-2)

Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2

Answer:

c=0
try:
    for i in range(len(s)):
        if s[i]+s[i+1]+s[i+2]=="bob":
            c+=1
except IndexError:
    pass
print("Number of times bob occurs is:",c)

Logical interpretation:

  • assigning a counter c

  • Using try and except

  • for each iteration in s:

    • if the letters on positions 0, 1, and 2 spells 'bob'

      • increase c as we found bob!

  • since we are indexing the string ahead of the loop, we need to catch IndexError.

  • Print it!

“Make it work, make it right, make it fast.” – Kent Beck

69 views

Comments


bottom of page