4. digit_sum variations

#1

I am just curious to see what solutions other users have come up with. Is mine the exact way the instructions ask it to be completed?

My code:

def digit_sum(n):
x = 0
a = str(n)
for i in a:
x += int(i)
return x

#2

there are multiply ways to solve a problem, and none of them are perfect. There is rarely a perfect answer. There are multiple factors (readability, maintainability, efficiency and so on) which play a part.

Each solution has its pros and cons. Certain solution will certainly be better then others (more pros and less cons)

#3

If anyone is interested in showing me alternative ways that they solved this, I think it would help benefit my understanding of different ways to solve these problems

#4

If you want to see alternative ways, you can just google them. This has been a much solved problem

but its more fun to see if you can come up with another solution yourself.

#5

I took the “convert the number into a string” route:

``````def digit_sum(n):
total = 0
n_list = []
string_of_n = str(n)
for x in string_of_n:
n_list.insert(0, int(x))
total = sum(n_list)
``````

#6

I would recommend coming back later to this solution and try to optimize it, which is possible in several ways.

#7

You’re absolutely right. I was able to get it a smidge shorter (and more readable) after playing around with it a bit:

``````def digit_sum(n):
total = 0
all_nums = list(str(n))
for each_num in all_nums:
total += int(each_num)
``````

#8

why would you convert to list? we can also perfectly iterate over a string

#9

My solution:

``````def digit_sum(n):
n > 0
dsum = 0
for i in str(n):
dsum = dsum + int(i)
return dsum
``````

#10

Here’s my solution:

``````def digit_sum(n):
result = 0
for number in str(n):
result += int(number)
return result
``````

#11

Are we posting solutions only? I suppose i should join then. We could use math only, which saves us string/integer conversion:

``````def digit_sum(n):
total = 0
while n > 0:
total += n % 10
n = n // 10

print digit_sum(434)
``````

or we could use a generator expression (which hands us the numbers one by one, not constructing a list in memory), which is effective:

``````def digit_sum(n):
return sum(int(i) for i in str(n))

print digit_sum(434)
``````

i think ideally, we should do the string conversion outside the loop:

``````def digit_sum(n):
n = str(n)
return sum(int(i) for i in n)

print digit_sum(434)
``````

to ensure string casting to a string isn’t needed each iteration of the loop

#12

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