T-Dot1992 T-Dot1992 - 1 month ago 6
Python Question

How to convert numbers in a string without using lists?

My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.

The function should look like this when operating:

>>> sum_numbers('34 3 542 11')
590


Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.

I tried the following code but they don't work:

>>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total


>>> sum_numbers('1 2 3')
'11'


Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.

I also tried using a
map()
function but I just got the same results:

>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total


>>> sum_numbers('1 2 3')
'11'

Answer

Totally silly of course, but for fun:

s = '34 3 542 11'

n = ""; total = 0
for c in s:
    if c == " ":
        total = total + int(n)
        n = ""
    else:
        n = n + c
# add the last number
total = total + int(n)

print(total)
> 590

This assumes all characters (apart from whitespaces) are figures.

Comments