4. digit_sum


#1



Hello everybody. For some reason I am getting an error message for my code on this exercise, but it works when I check it. Any suggestions would help a lot. Thanks.


a = []
def digit_sum(n):
    b = str(n)
    for x in b:
        c = int(x)
        a.append(c)
    x = sum(a)
    return x


#2

>>> digit_sum(123)
6
>>> digit_sum(123)
12
>>> digit_sum(123)
18
>>> digit_sum(123)
24
>>> digit_sum(123)
30

#3

@n0tar0b0t

What @ionatan is implying is that your variable a is at the global level and is never garbage collected. So each time you run the function it still has the value from the last session stored.
As such you either need to put that specific variable into the function or you need to zero out the variable each time you start that function. Doing so should allow you to have a functioning function!


#4

This works well!!

def digit_sum(n):
a = str(n)
print a
ad=0
for x in a:
ad=ad+int(x)

return ad

#5

This seems to work for me:

def digit_sum(n):
    a = str(n)
    b = 0
    for i in a:
        b += int(i)
    return b
    
print digit_sum(55)
print digit_sum(23)

Steps:
1. Turn n into a string to separate each individual number in n and name that string a.
a = str(n)
2. Create a variable named b to store the sum of those individual numbers and set it to zero.
b = 0
3. Loop through the separated numbers i in the string a and add them to the variable b while also converting them back to integers.

for i in a:
        b += int(i)

4.Then return "b".
return b

I like being able to see the results so I have two calls to the function.

I guess it's pretty much the same as what pyslayer19619 has.


#7
just to practice another method, this works too

def digit_sum(n):
    start=0
    while n//10!=0:
        start=start+(n%10)
        n=n//10
    else:
        start+=n
    return start
    
print digit_sum(1234)

#10

This worked for me:

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

#11

Thank you! I've been combing through these forums trying to find a simple code for this. I knew all the ones I was coming across were unnecessarily complex.

You relieved a lot of my stress lol


#12

My pleasure! I try to explain things in everyday common language as well which most brilliant coders neglect to do. I'm just a beginner right now. But I think that it's hard enough learning this as is so there's no reason people should have to translate an explanation. For those who want to teach and explain the concepts they need to learn to communicate on a basic level otherwise they've wasted everyone's time, no one learns, and no one respects that. Sorry for the rant. I'm just passionate about good communication and not going over everyone's head with advanced terminology in explanations. Oh and don't get me started on links to novel length explanations...

Side note though: Unfortunately I read on the rules for using Codeacademy the other day we're not allowed to post answers. Quite a bummer. I disagree with that train of thought for several reasons. Mainly because showing the answer and explaining how it was achieved the best way saves time and money as well as teaches the better or best way to accomplish the task. When you teach people your trade to make them similar to you you show them what you know and how you do it. You wouldn't let them flounder for years only to turn out a half assed version of what you are. That doesn't make sense. Oh well not my website so their word is final.

P.S. netstereo's version looks like the best way!! Very nice if that works!!!


#13

Wow, I was struggling with this for a while. I had code almost exactly the same as those above that work, but instead of "return result" from the for loop I had "print result". What difference does that make?


#14

A rhetorical question, I'm guessing? Yes, a huge difference. It hints at a practice worth noting... Don't leave it up to the functions to perform output operations unless that is their sole purpose. Functions are utilities and they run so much better (meaning way faster) if there is no output to update. Push in some data, get a return value/object reference, then work out the display aspect.

But it's more than just that, we have a retained copy/reference of/for the return value. Print doesn't store anything to anywhere but the display or standard output. If we don't return it, once the function is exited it is lost.


#15

Refactoring along the general principles included in your program,

def digi_sum(n, r = 0):
    try:
        n = int(n)
        while n > 0:
            r += n % 10
            n //= 10
        return r
    except:
        raise ValueError

This will accept both numbers and string representation of numbers.

print digi_sum(123456789)      # 45
print digi_sum('123456789')    # 45

It will work on floats, but only the integer portion. A little more hoop jumping would be needed to work with floats, but it wouldn't be that difficult, I suspect.


#16

I wish I could say it's rhetorical. So would it be right to say that return is a way of determining what the information is, but print is a method of displaying the information?


#17

...and only a method of displaying, nothing more. return is how we give information back to the program.