Home Ask Login Register

Developers Planet

Your answer is one click away!

Jorge Gandara 2 weeks ago

How can I add a list of intergers together using a comprehension?

I'm trying to convert a number to a string, then to a list, then converting the list of numbers into integers, then adding these numbers together.

Here's an example:

Number = 123456789
SplitList = (list(str(Number)))
IntergerList = list(int(I) for I in SplitList)
A = 0
A = (A + S for S in IntergerList)

Why doesn't this work?

Answers


Mureinik 2 weeks ago

Why reinvent the wheel? Just use the built-in sum function:

sum(integerList)


Håken Lid 2 weeks ago

You can do it by passing a generator expression to the builtin function sum.

number = 123456789
sum(int(digit) for digit in str(number))


nknous 2 weeks ago

numbers = 123456789
splitNumbers = [int(d) for d in str(numbers)]


sumOfSplitNumbers = sum(splitNumbers)


Damian Lattenero 2 weeks ago

Why transform it to a list? This is a math problem, do the maths :), it's another option just only another:

Number = 123456789
res = 0
while(Number != 0):
  res += Number % 10
  Number = int(Number / 10)

res = 45

Post Status

Asked in 2 weeks ago
Viewed 2,709 times
Voted 8
Answered 4 times

Search




Leave an answer


Quote of the day: live life