4/15 digit_sum


#1

Hello all,

Can someone explain to me why my code is doing this and how to fix it?

def digit_sum(n): 
    digit_string = str(n) 
    for i in digit_string: 
        digit_list.append(i)
        int_list = map(int, digit_list)
        sum_list = sum(int_list)
        print sum_list
        
digit_sum(454)

Output is this
4
9
13
None

Error is: Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11.

I am not sure how to get the last list, the one with all of the numbers in the list, instead of the numbers being put in individually and that list being displayed. To clarify, how can create just one list instead of multiple lists?


#2

Well, you are creating only one list (digit_list), but you print the result after every digit. Why? Because your print statement is in the body of the for loop.

def digit_sum(n):
    digit_list = []
    digit_string = str(n) 
    for i in digit_string: 
        digit_list.append(i)
    int_list = map(int, digit_list)
    sum_list = sum(int_list)
    print sum_list

digit_sum(454)

This code is not correct yet. According to the error message your function should return the result, not print it out to the console.


#3

Thanks so much for your input!

My new code works great!

def digit_sum(n): #define our funtion
    digit_list = [] #create a new empty list
    digit_string = str(n) #convert digits to strings
    for i in digit_string: #runs through the numbers in list of                                   strings
        digit_list.append(i) #adds the numbers(strings) to the new                                list 
        int_list = map(int, digit_list) #converts every string to an                                          integer from the digit_list
        sum_list = sum(int_list) #adds all of the values from the list
    return sum_list    #returns the final list with our answer
print digit_sum(1500)

#4

Just sharing the code I wrote on top of my head for this exrecise, didn't optimize it to be short, to say the least. :slightly_smiling:
It works fine in the actual python interpreter but fails to pass the exercise .
I didn't use str conversion :).

Cheers.

`import time

def digit_sum(x):
numbers = []
original_number = x
while x > 0:
tmp = x % 10
numbers.append(tmp)
print "Added '{0}' to the list".format(tmp)
x = x // 10
print "So far we have the following numbers: '{0}'".format(numbers)
print "Calculating...\n............."
time.sleep(5)
print "the sum of all the digits in your number ('{0}') is: '{1}'".format(original_number, sum(numbers))

digit_sum(2823)
`


#5

You're very welcome :slightly_smiling:

Your code looks great, but you can optimize it a bit. Please note that these two operations:

int_list = map(int, digit_list) #converts every string to an integer from the digit_list
sum_list = sum(int_list) #adds all of the values from the list

are inside the for loop. This means that they are executed after addition of every digit. Is this necessary? Not really. You can execute them only once, after the for loop :slightly_smiling:


#6

Is line 5 the reason why this is failing with two numbers? It works if I set n individually...

  1. num=[]
  2. def digit_sum(n):
  3. total = 0
  4. for i in range(0,len(str(n))):
  5. total += (n//10**i)%10
  6. else:
  7. num.append(total)
  8. print num

Thanks in advance


#7

The problem is that variable num is defined globally. After first execution of your function this variable has some value and that is why second function call will return incorrect result. You should move definition of this object to the scope of digit_sum function.

And you should print the result as integer, not as a list.

I would suggest you to try to answer this question - do you really need num variable? I mean, whole digit sum is stored inside the total variable, right? :slightly_smiling:


#8

Hi, would you like to review my code below? it gives the right result, but if i compare to your codes above, mine was really different. Do you see any weaknesses of this code:

def digit_sum(n):
    nlist = []
    n = str(n)
    for number in n:
        nlist.append(number)
    new_list = [int(number) for number in nlist]
    now = sum(new_list)
    return now

many thanks before :slightly_smiling:


#9

Looks good to me... (i am using it since I can't get over mine) :confused:

def digit_sum(n):
total = 0
print n
for i in range(0,len(str(n))):
total += (n//10**i)%10
else:
print total

digit_sum(n)
434
11


#10

Your code is correct, but it can be easily improved :slightly_smiling:

Please note that string is already a list of the characters. That is why nList and the first for loop is not needed.

def digit_sum(n):
    n = str(n)
    new_list = [int(number) for number in n]
    now = sum(new_list)
    return now

And now is the question - do we really need all these variables? Nope. Remember that if you use a variable only in one place - you don't need it. Let's make this code more pythonic :slightly_smiling:

def digit_sum(n):
    return sum([int(number) for number in str(n)])

#11

I see,

That's really simpler than i thought!

Thank you yaa!!
:relaxed:


#12

You're very welcome :slightly_smiling:


#13

I got how it works with a list, however when I tried without a list, and a variable "total" instead, it doesn't work and I can't figure out why

def digit_sum(n):
    string_n = str(n)
    for x in string_n:
        total = 0
        int(x) += total
    return total

#14

total = total + int(x)

Doing the other way around doesn't work in Python.


#15

thank you there, it is fixed :slightly_smiling: also I realized total = 0 need to be outside the loop


#16

No problem, Benjamin! Glad to help!


#17

This is nearly the same as what I did:

def digit_sum(n):
total=0
digit_str = str(n)
for i in digit_str:
total += int(i)
return total


#18

Here is my code. It works well. Hope it helps.


#19

Hope it helps:

  def digit_sum(n):
        total = 0
        while (n//10)!=0:
           total += (n%10)
           n=n//10
        total +=n 
        return total

#20

Did it work for you @gigaace79222? Because i get the message **Your function fails on digit_sum(434). It returns 4 when it should return 11 **
my code is:

def digit_sum(n):
    total = 0
    digi_string = str(n)
    for i in digi_string:
        total = total + int(i)
        return total