Python.The problem is in solving the problem with cycles

79 Views Asked by At

The sum() function takes a series of numbers (a string) and returns their sum.

def sum(numbers):
    result = 0
    for num in:
        result += 
    return result

sum("12345")  # 15

I started learning the language recently. In one of the sites I came across this problem that I can not solve.

def sum(numbers):
    result = 0
    for num in numbers:
        result += 1

This is how I see the solution to this problem, but it is not correct.

5

There are 5 best solutions below

2
Talha Tayyab On BEST ANSWER

You have to convert str num to int before adding:

def sum1(numbers):
    result = 0
    for num in numbers:
        result += int(num)  # add each number from numbers
    return result

sum1('12345')

#15
0
pang2016 On
def sum(numbers):
    result = 0
    for num in numbers:
        result += int(num)
    return result

the num should convert to int type

0
SIGHUP On

First of all, do not define functions that use the same name as a Python built-in function (unless you have a very good reason to override it).

In this case you need to convert each character in the string to an integer then sum those integers. You can achieve this as follows:

def my_sum(s: str) -> int:
    return sum(map(int, s))

print(my_sum('12345'))

Output:

15
0
sahasrara62 On

You need to iterate on numbers, for each digit which is in str format convert it to int and then sun that to final result.

def sum(numbers):
    final = 0
    for num in numbers:
        final += int(num)
    return final
2
Iron filings On

It is somewhat unclear exactly what you are asking. For one thing, the first function you provide is invalid python, specifically the line:

for num in:

This needs some collection that you are iterating through after the in. The line:

result +=

is also malformed, it needs a value after the += that will be added to the result. Based off context, I assume you mean the first function to say:

def sum(numbers):
    result = 0
    for num in numbers:
        result += num
    return result

Also, the way you call the function is incorrect. The value "12345" is not a list containing the values 1 through 5, but a string containing the text "12345". The expression sum([1, 2, 3, 4, 5]), using list syntax, will give the correct result of 15.

As for your second implementation of sum, it is also incorrect. Syntactically it is fine, but the line result += 1 should read result += num. By adding only 1 to the result for each element, you are merely counting the number of elements, but to find the sum you must add each element itself.