Practice makes perfect - digit_sum


#1


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

Can someone please tell me why I'm getting this error?
'Oops, try again. Your function fails on digit_sum(434). It returns 8 when it should return 11.'


def digit_sum(n):
    results = 0

    for i in range(0,len(str(n))):
        if n / (10**(i+1)) >= 1:
            results += (n % (10 ** (i+1)))/(10**(i))
            n = n // 10**(i+1)
        else:
            results += n/(10**i)
    return results


#2

Nvm I replaced

n = n // 10**(i+1)

with

n = n - (n % (10 ** (i+1)))/(10**(i))

and it worked :slight_smile:


#3

That's a constant value, i cancels itself out - you're doing a lot of operations that are not required. You don't need to use exponents at all.


#4

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