digit_sum


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096
Oops, try again. Your function fails on digit_sum(434). It returns 1302 when it should return 11.
i was expecting for n to become variable m changing the value of n to a string so it could be iterable so that in the for loop j makes m an integer and then i append to the empty list l
and then return the sum of list L


def digit_sum(n):
    l=[]
    m=str(n)
    for i in m:
        j=int(m)
        l.append(j)
    return sum(list(l))


#2

In the line
j=int (m)

Change m to i

i represents the digit in the string m.
i.e. i represents the item in the list m


#3

thanks bro ... it worked


#4

Did take me some while but I got it to work with any value.
Thought would be nice to share.:smiley:

if n is -123
give you an error
Traceback (most recent call last):
File “”, line 8, in
File “”, line 5, in digit_sum
ValueError: invalid literal for int() with base 10: ‘-’

if n is 12.3
Traceback (most recent call last):
File “”, line 8, in
File “”, line 5, in digit_sum
ValueError: invalid literal for int() with base 10: ‘.’

To make it run always with negative and/or floats

def digit_sum(n):
    l=[]
    m=str(n)
    m=m.translate(None, ".,-")
    for i in m:
        j=int(i)
        l.append(j)
    return sum(list(l))

print digit_sum(-12.5)
Code
# https://discuss.codecademy.com/t/digit-sum/33637/3
# study by @jeanpauljaspers

def digit_sum(n):
    l = []
    m = str(n)
    m = m.translate(None, ".,-")
    for i in m:
        j = int(i)
        l.append(j)
    return sum(list(l))
    
print digit_sum(-12.5)

#6

Thank you for the help here! Can you walk me through the translate function, and what you have in between the parenthesis? Everything else seems to make sense.

Update: the m. tells you what to translate, correct?

And the None is included because you don't need a table for strings, right?

And the ".,-" is what is being removed from any string of numbers, in this case negatives, thousands with the comma, and decimals or floats, right?

Calling the translate function where you did translated into a string that can be easily converted into integers, for the summing of each characther.

In the for loop, you turned each character into an integer, and then appended each integer to list l, and then summed the contents of list l.

Is that right?


#7

I used the translate function to make sure that all I'm left with is a number in string form.
The assignment was for positive outcome only.
So this ".,-" takes care of that in the translate function.
As I understand the function, if you use NONE it will remove what is between the parentheses.

Everything was like you wrote.
The m. Is the string on which the function will perform the action.