Practise makes perfect digit_sum


#1

def digit_sum(n):
if n > 0:
m = str(n)
y = list(m)
for x in y:

this is what i have so far in this one. im stuck confused. can someone point me in the correct direction thanks.


4/15 Why wouldn't this code work for this problem?
#2

When stuck, try reading what you are trying to achieve out loud, sometime it can helps seeing the problem from a different angle.

If I read your code it goes like this:

def digit_sum(n):
    if n > 0:                # if the number i'm trying to sum is greater than zero
        m = str(n)           # put a string representation of it into m
        y = list(m)          # then make a list from m and put it into y
        for x in y:          # for each item in list y...

One thing i immediately notice is that you don't need to create a list from a string as each of its character is already accessible as a list item, like so:

string = "Hello"

for i in range(len(string)):
    print string[i]

so we can get rid of

y = list(m)

Now that you can access each number of a digit individually, how would you go about adding them all together?

Perhaps by adding them to an aptly named variable:

sum = 0            # declaring our empty sum

adding to a running tab, surely you did already in previous exercises...

for each in digit
   sum += digit    # adding each digit to it

Make your function return that variable and you should be well on your way to the next exercise... :smile:


#3

@denisaltroy

That is a good way to go about it most definitively.

@killerdevildog11

After a bit you can do things like the following.

What the following code does is converts the int item of a number into a string. The reason for this is that we need to be able to iterate over each number and we cannot do that if it is an integer type.

After we convert it the next thing that takes precedence is the for loop, with each x getting assigned a value depending on where it is in the index of our a variable.

The last thing it does is to take that index positions variable and convert it back into a int and inserts it into a list.

After all that is done we pass the list to the sum() built-in function and return it's value all in one neat little line of code.

def return_sum_of_digits(a):
    return sum([int(x) for x in str(a)])

Best of luck!


#4

Thanks for pointing that out @zeziba, wrapping it all up in a one-liner is definitely the next step after getting confortable and understanding the broken-down incarnation of a problem!


#5

@denisaltroy

so i get the

for i in range(len(string)):
print string[i]

and put that into my code

def digit_sum(n):
if n > 0:
m = str(n)
the_sum = 0
for i in range(len(m)):
the_sum = the_sum + i
return the_sum

and it gives me this error.
Oops, try again. Your function fails on digit_sum(434). It returns 0 when it should return 11.


#6

assume the indentation is correct.


#7

Hi @killerdevildog11,

What this tells us is that there is a problem with your for loop. When stumbling on an error, it always helps to add debugging info to understand what's going on under the hood. Let's print a few things to the console to try and break down every step of your program:

def digit_sum2(n):
    if n > 0:
        m = str(n)
        the_sum = 0
        for i in range(len(m)):
            print "the_sum is: " + str(the_sum)
            print "adding i: " + str(i)
            the_sum = the_sum + i
            print "the_sum is now: " + str(the_sum)
            print
    return the_sum 
    
print digit_sum2(434)

this will return:

the_sum is: 0
adding i: 0
the_sum is now: 0

the_sum is: 0
adding i: 1
the_sum is now: 1

the_sum is: 1
adding i: 2
the_sum is now: 3

3
None

Can you see what's happening? Why is it adding 0 through 3 instead of 4, 3 and 4?

Your code is adding i to the sum but i is in fact each number in the range between 0 and the length of your string m which is 3... So you're doing:

the_sum = 0
the_sum = 0 + 0
the_sum = 0 + 1
the_sum = 1 + 2

Now what we want is to add each digit in our three digits number right? Here's how you adress each character of a string:

string = "word"
print string[0]    # will return "w"
print string[1]    # will return "o"
print string[2]    # will return "r"
print string[3]    # will return "d"

Clearer now?

I'm sure you can pick it up from here... :smile:


#8

Here's a little trick:

Whenever you would like to paste code and have it remain its format and indentation, since this forum supports Markdown, you can use three backticks before and after your code block like so:

```
def my_func(x):
my_var = 0
sum = my_var + x
return sum
```

and it will render in an easy to read fashion:

def my_func(x):
    my_var = 0
    sum = my_var + x
    return sum

#9

@ denisaltroy

i think i got it now... i had to write all of this down on paper to see what i was trying to do.

would this work then?

def digit_sum(n):
result = 0
str_n = str(n)
print str_n
if n > 0:
print str_n
list_n = list(str_n)
for i in range(len(list_n)):
y = int(list_n[i])
print y
result = result + y
print result
return result

print "this is a test.", digit_sum(1234)


#10

again assume the indentation is correct.


#12

def digit_sum(n):
    result = 0
    str_n = str(n)
    print str_n
    if n > 0:
        print str_n
        for i in range(len(str_n)):
             y = int(str_n[i])
             print y
             result = result + y
             print result   
    return result

sorry wanted to test that backtick trick and cleaned up the code. I found that this works.


#13

Yep! Good job.

Another litte trick. While what you did works well, there's a shortcut for it:

# This reassigns "result + y" to "result"
result = result + y

# will yield the same result as but can be read as "increment result by y"
result +-= y

and it works for other operands as well

# This will "decrement result by y"
result -= y

# this will "multiply result by y"
result *= y

# and you guessed it, this will "divide result by y"
result /= y

Hope you'll find it useful!