# Digit_sum improve

#1

Hey guys, I wanted to get the numbers by using mod and floor div, as the hint says, this is what I did and it works but I was wondering if there's extra code that I should get rid of or if it's right actually. Thanks!

``````def digit_sum(n):
desc = []
nfinal = 0
while n > 0:
desc.append(n % 10)
n = n // 10
for x in desc:
nfinal += x
return nfinal``````

#2

We won't need an extra data structure. The sum can be accumulated in the single loop.

``````total = 0
while n > 0:
total += n % 10
n //= 10

#3

For your Future references and thinking:

A one line solution for python 3x. In python 2x "reduce" a built-in function so skip the 1st line.

``````from functools import reduce
def digit_sum(n):
return int(reduce(lambda x,y: int(x) + int(y), list(str(n))))``````

Goes over the head right now but after quite a few practice and learning you'll be shocked how easy this is.

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.