How to convert numbers to string without using lists?

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

The function should look like this:

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

Typically, such a function is easy to create using lists and list methods. But trying to do it without using them is a nightmare.

I tried the following code, but they do not 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 to integers and added together, instead I get the string "11". In other words, the numbers in the string still have not been converted to integers.

I also tried using the function map(), but I got only 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'
+4
8

, , :

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

, ( ) .

+6

, : , . ( ) , , , - :

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` last value to the sum and return.
    sum += convert_s_to_val(current)
    return sum

, str.split():

def sum_numbers(s):
    return sum(map(float, s.split()))
+2

( ) :

def sum_string(string):
    total = 0

    if len(string):
        j = string.find(" ") % len(string) + 1
        total += int(string[:j]) + sum_string(string[j:])

    return total

, OP, :

import re

def sum_string(string):
    pattern = re.compile(r"[-+]?\d+")

    total = 0

    match = pattern.search(string)

    while match:

        total += int(match.group())

        match = pattern.search(string, match.end())

    return total

< >

>>> sum_string('34 3 542 11')
590
>>> sum_string('   34    4   ')
38
>>> sum_string('lksdjfa34adslkfja4adklfja')
38
>>> # and I threw in signs for fun
... 
>>> sum_string('34 -2 45 -8 13')
82
>>> 
+1

:

def sum_numbers(s):
    sm = i = 0
    while i < len(s):
        t = ""
        while  i < len(s) and not s[i].isspace():
            t += s[i]
            i += 1
        if t:
            sm += float(t)
        else:
            i += 1
    return sm

:

In [9]: sum_numbers('34 3 542 11')
Out[9]: 590.0

In [10]: sum_numbers('1.93 -1 23.12 11')
Out[10]: 35.05

In [11]: sum_numbers('')
Out[11]: 0

In [12]: sum_numbers('123456')
Out[12]: 123456.0

, :

def sum_numbers(s):
    prev = sm = i = 0
    while i < len(s):
        while i < len(s) and not s[i].isspace():
            i += 1
        if i > prev:
            sm += float(s[prev:i])
            prev = i
        i += 1
    return sm

itertools.groupby, , :

from itertools import groupby


def sum_numbers(s):
    allowed = set("0123456789-.")
    return sum(float("".join(v)) for k,v in groupby(s, key=allowed.__contains__) if k)

:

In [14]: sum_numbers('34 3 542 11')
Out[14]: 590.0

In [15]: sum_numbers('1.93 -1 23.12 11')
Out[15]: 35.05

In [16]: sum_numbers('')
Out[16]: 0

In [17]: sum_numbers('123456')
Out[17]: 123456.0

, ints, str.isdigit :

def sum_numbers(s):
    return sum(int("".join(v)) for k,v in groupby(s, key=str.isdigit) if k)
+1

:

def sum_numbers(s):
    sum = 0
    #This string will represent each number
    number_str = ''
    for i in s:
        if i == ' ':
            #if it is a whitespace it means
            #that we have a number so we incease the sum
            sum += int(number_str)
            number_str = ''
            continue
        number_str += i
    else:
        #add the last number
        sum += int(number_str)
    return sum
0

:

def nums(s):
    idx=0
    while idx<len(s):
        ns=''
        while idx<len(s) and s[idx].isdigit():
            ns+=s[idx]
            idx+=1
        yield int(ns)
        while idx<len(s) and not s[idx].isdigit():
            idx+=1

>>> list(nums('34 3 542 11'))
[34, 3, 542, 11]

:

>>> sum(nums('34 3 542 11')) 
590

re.finditer :

>>> sum(int(m.group(1)) for m in re.finditer(r'(\d+)', '34 3 542 11'))
590

...

0
def sum_numbers(s):
    total=0
    gt=0 #grand total
    l=len(s)
    for i in range(l):
        if(s[i]!=' '):#find each number
            total = int(s[i])+total*10
        if(s[i]==' ' or i==l-1):#adding to the grand total and also add the last number
            gt+=total
            total=0
    return gt

print(sum_numbers('1 2 3'))

0

If we omit the fact of evil , we can solve this problem with it.eval

def sum_numbers(s):
    s = s.replace(' ', '+')
    return eval(s)

Yes, that’s easy. But I will not do this in production.

And be sure to check that:

from hypothesis import given
import hypothesis.strategies as st


@given(list_num=st.lists(st.integers(), min_size=1))
def test_that_thing(list_num):
    assert sum_numbers(' '.join(str(i) for i in list_num)) == sum(list_num)

test_that_thing()

And it won’t bring anything.

0
source

Source: https://habr.com/ru/post/1657208/


All Articles