def add_numbers_in_string(s):
'''
Given a string of text containing numbers separated by
spaces, returns the sum of the numbers.
'''
total = 0
num_list = s.split()
for item in num_list:
num = int(item)
total += num
return total
# Alternate version uses the find() method to find the
# next space
def add_numbers_in_string_alt(s):
total = 0
s.strip() # get rid of any leading or trailing whitespace
while s.find(" ") > 0: # as long as we find another space
index = s.find(" ")
item = s[:index] # up to index is one number
s = s[index + 1:] # get rid of the part we just read
s = s.strip()
num = int(item)
total += num
# loop above misses the last item, add it now
num = int(s)
total += num
return total
# This version goes into an infinite loop, since when it
# gets to the last number in the list there is no space
# to find, and the line s = s[index + 1:] leaves s unchanged.
def add_numbers_in_string_bad(s):
total = 0
s.strip()
while len(s) > 0:
index = s.find(" ")
item = s[:index] # up to index is one number
s = s[index + 1:] # get rid of the part we just read
s = s.strip()
num = int(item)
total += num
return total
def sum_string(s):
total = 0
s = s.strip()
while len(s) > 0:
index = s.find(" ")
if index > 0:
total = total + int(s[:index])
s = s[index + 1:]
s = s.strip()
total = total + int(s)
return total
result = add_numbers_in_string_alt("2 13 137 50")
print(result)