Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

def num_space_runs1(s): \"\"\"Returns: The number of runs of spaces in the strin

ID: 3836886 • Letter: D

Question

def num_space_runs1(s):
"""Returns: The number of runs of spaces in the string s.

A run is a collection of adjacent spaces. We need a non-space character
in between to break up runs.

Example: num_space_runs(' a f g ') returns 4
num_space_runs('a f g') returns 2
num_space_runs(' a bc d') returns 3

Parameter s: The string to parse
Precondition: s is a nonempty string with letters and spaces"""

# STUDENTS: The invariant for you to work with is:
# s[0..i-1] has n runs of spaces, AND:
# in_a_run is a boolean:
# True if i-1 is a valid index and s[i-1] is a space
# False otherwise
#
# In other words, s[i..len(s)-1] still needs to be checked;
# and in_a_run tells us whether a new space would be part of an old run.


# REPLACE THE FOLLOWING WITH CORRECT INITIALIZATION CODE:
i = None
n = None
in_a_run = None

# PUT YOUR WHILE LOOP HERE
# Hint1: you only need to increment n when you find a space and you are
# not currently in a run.
# Hint2: you need to change in_a_run when:
# (a) you have found a space and you are not currently in a run, or
# (b) you found a non-space and you currently in a run
# Hint3: don't forget to increment your loop variable, if you have one!

# post: s[0..len(s)-1] contains n runs of spaces
# PUT THE RETURN STATEMENT HERE

Explanation / Answer

def num_space_runs(inputStr):
   n=0
   in_a_run = False
   for index in range(len(inputStr)): # loop through the string
       if index+ 1 < len(inputStr) and inputStr[index+ 1] == " ": # check if there are immediate spaces.
           in_a_run = False # set in_a_run value to False if there are immediate spaces
       else:
           in_a_run = True # set in_a_run value to True if there is a non space
       if inputStr[index] == " " and in_a_run == True: #increment only when there is a non-space character after a space
           n = n +1 # count
      
   return n

  
  
  
  
  
  
print num_space_runs(" a f g ") # for testing

print num_space_runs('a f g') # for testing

print num_space_runs(' a bc d') # for testing