In: Computer Science
Assume you already have a non-empty string S, which is guaranteed to contain only digits 0 through 9. It may be of any length and any number of digits may occur multiple times. Starting from the front of the string, write a loop that jumps through the characters in the string according to the following rule: Examine the current character and jump that many characters forward in the string Stop if you jump past the end of the string, or if you ever land on a 0 Keep track of how many characters are examined during this jumping process (including the final 0). Associate the answer with a variable called charCount. Example 1: For S = "11011", you will examine 3 characters (the first two 1s and then the 0. The last two 1s will not be examined). Example 2: For S = "3120" you will examine 2 characters (seeing the first 3, you will jump 3 spaces to the right and land on the 0). Example 3: For S = "11111" you will examine 5 characters.(in python)
Python Program:
""" Python program that counts the number of characters examined
"""
# Reading string
S = input("Enter S: ")
# Iterating over String
len = len(S)
# Counter for characters examined
examinedCharacters = 1
# Set position to 0
pos = 0
# Loop till all characters are examined or 0 is
encountered
while True:
# Fetching starting number
val = int(S[pos])
# Calculating ending position
end = pos + val
# Checking ending character
if end >= len:
break
elif S[end]=='0':
examinedCharacters=examinedCharacters+1
break
else:
examinedCharacters=examinedCharacters+1
# Updating position
pos = end
print(examinedCharacters)
__________________________________________________________________________________________
Sample Run: