Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 604
MountainSlayer Avatar asked Oct 09 '16 16:10

MountainSlayer


2 Answers

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.

like image 111
Jacob Vlijm Avatar answered Oct 18 '22 00:10

Jacob Vlijm


You've definitely put some effort in here, but one part of your approach definitely won't work as-is: you're iterating over the characters in the string, but you keep trying to treat each character as its own number. I've written a (very commented) method that accomplishes what you want without using any lists or list methods:

def sum_numbers(s):
    """
    Convert a string of numbers into a sum of those numbers.

    :param s: A string of numbers, e.g. '1 -2 3.3 4e10'.
    :return: The floating-point sum of the numbers in the string.
    """
    def convert_s_to_val(s):
        """
        Convert a string into a number. Will handle anything that
        Python could convert to a float.

        :param s: A number as a string, e.g. '123' or '8.3e-18'.
        :return: The float value of the string.
        """
        if s:
            return float(s)
        else:
            return 0
    # These will serve as placeholders.
    sum = 0
    current = ''
    # Iterate over the string character by character.
    for c in s:
        # If the character is a space, we convert the current `current`
        # into its numeric representation.
        if c.isspace():
            sum += convert_s_to_val(current)
            current = ''
        # For anything else, we accumulate into `current`.
        else:
            current = current + c
    # Add `current`'s last value to the sum and return.
    sum += convert_s_to_val(current)
    return sum

Personally, I would use this one-liner, but it uses str.split():

def sum_numbers(s):
    return sum(map(float, s.split()))
like image 43
Pierce Darragh Avatar answered Oct 17 '22 23:10

Pierce Darragh