4. digit_sum: list


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#


My code doesn't work but my point is that I was wondering if it is possible to transform the number n into a list and then loop through the list to add each item of this list...


def digit_sum(n):
    my_list=[]
    my_sum=0
    
    for i in n:
        my_list.append(str(n))
    for i in my_list:
        my_sum=my_sum+ int(i)
    return my_sum


#2

Sure, you can turn number n into list of digits (in the string form) by turning it into the string - str(123456).

You can also use a list comprehension to turn n into a string and create list of digits in the numerical form:

n = 123456
list_of_digits = [int(c) for c in str(n)]

Or you can write a simple function to create list of digits in the numerical form:

def list_of_digits(n):
  result = []
  while n:
    digit = n % 10
    result.append(digit)
    n //= 10
  return result

One of the solutions:

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

The main problem in your function is that you can't iterate through the integer. You have to turn it into a string (in this case you have to remember about converting every digit into int) or a list of digits.


#3

thanks! And what in the reasoning is wrong if we try to transform n into a string by simply doing:
n= str(n)
?


#4

def list_of_digits(n):
result = []
while n:
digit = n % 10
result.append(digit)
n //= 10
return result

in this block you create the list with the different items. but can you do something to add the items other than return sum(result)? why can't we simply do:
sum_digits=0
for i in result:
sum_digits += i
return sum=digits


#5

thanks! And what in the reasoning is wrong if we try to transform n into a string by simply doing:
n= str(n)
?

Nothing, you just have to remember that you work with strings. You can't just do:

n = 123456
result = 0
for i in str(n):
    result += i

You have to remember to turn a digit (i) into a int before adding it to the result:

n = 123456
result = 0
for i in str(n):
    result += int(i)

in this block you create the list with the different items. but can you do something to add the items other than return sum(result)?

Of course, we can do that. I just wanted to show how to create list of digits to answer first part of your question. To calculate the sum we just need to change few things:

def digit_sum(n):
  result = 0
  while n:
    digit = n % 10
    result += digit
    n //= 10
  return result

#6

I see, one of my problem was also that I set the sum "result" outside the function so when I called it i guess the variable result was not known
result = 0
def digit_sum(n):
for i in str(n):
result += i
return result


#7

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