Math domain error in digit_sum challenge


#1



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


I get thrown a math domain error with the code below when it's in code academy. If I run it in a normal python environment then it works perfectly. I'm wracking my brain to figure out what I'm doing wrong here.

For the record, I know the commented version is much much simpler. But I'm still curious as to what I'm doing wrong with the more complicated approach.


'''
def digit_sum(n):
    sumof = 0
    n = str(n)
    for x in range(len(n)):
        sumof = sumof + int(n[x])
    return sumof
'''

import math

def digit_sum(n):
    sumof = 0
    digits = 0
    
    digits = int(math.log10(n)) + 1
    
    print digits #debug
    
    for x in range(digits):
        sumof = sumof + n // (10**x) % 10

    return sumof


#2

You would have to test with the same input as was used when the math domain error was raised. Looks like you changed several things and attributed the difference in behaviour to the wrong change.


#3

Did you happen to input 0 for n? What if the SCT tests this value?


#4

Wow, I can't believe I overlooked this and didn't test 0 on my own. I added an exception for it and it runs perfectly. Thanks for bringing that to my attention.


#5

Found that the error was coming from Code Academy when it ran n as 0. Too simple, I'm kicking myself. Thanks for the input.


#6

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