4. digit_sum looking for a challenge (modulo and floor division)


#1


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


Error message:
"Traceback (most recent call last):
File "python", line 17, in
File "python", line 7, in digit_sum
IndexError: list assignment index out of range"


I am trying to do this using the method of % and // (modulo and floor division) described in the hint. I thought the problem might be that because n is changing inside the for loop, I could solve the problem by setting a fixed variable outside the loop for the length of n, but that did not help and I still get the same error message. Where am I going wrong?


def digit_sum(n): # Challenge version using modulo
    sum_of_digits = 0 # Set our var to zero to store the sum below
    digit = [] # Set up var "digit" as an empty list
    # Need to set a variable that will stay fixed and store starting length of n:
    start_n_len = len(str(n))
    for i in range(start_n_len):
        digit[i] = n % 10 # Take the ith digit from the right side and store it as digit[i]
        # Now we need to add this in a loop...
        sum_of_digits += digit[i]
        # ...and take the digit stored in digit[i] off of n
        # To do this, we will use // 10
        n = n // 10
    return sum_of_digits
    
    

print digit_sum(1234)


#2

if you really want to use modulo and floor division, you should never have to convert to string:

start_n_len = len(str(n))

yet you do

For this solution, a while loop is recommend. You also don't need a list


#3

Thank you! I was trying to make it much more complicated than it needed to be. Using your guidance, I was able to make it quite simple and elegant:

def digit_sum(n): # Challenge version using modulo
    sum_of_digits = 0 # Set our var to zero to store the sum below
    while n>0:
        sum_of_digits += n % 10
        n = n // 10
    return sum_of_digits

:smiley:


#4

My guidance was minimal, good that you solved :slight_smile: It well done, nice and elegant solution


#5

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