Digit_sum


#1



Please let me know, why it is behaving like this:

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


Oops, try again. Your function fails on digit_sum(434). It returns 22 when it should return 11.


it should print sum of digits and it is printing.


x = 0
y = 0
def digit_sum(n):
    while n:
        global x
        global y
        x=n%10
        y = y + x
        n = n/10
    return y
digit_sum(434)


#4

My code:

def digit_sum(n):
    if n >= 0:
        sum = 0
        while n:
            sum += n % 10
            n /= 10
        else:
            print sum
            return sum

Your code:

x = 0
y = 0
def digit_sum(n):
    while n:
        global x
        global y
        x=n%10
        y = y + x
        n = n/10
    return y
digit_sum(434)

Try and see what you did wrong.


#5

When your code is run in Python 3 it returns 12.222222222222216

Local variables are preferred. We only need one local variable.

This is readable, but not very explicit. A comparison is a little more obvious.

while n > 0:

The less obvious approach is to use floor division. Python 2 yields an integer when dividing two integers, but Python 3 returns a float. In both versions, floor division yields an integer.

def digit_sum(n):
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total

Now 434 returns 11.


#6

@turtwigpo 's code:

def digit_sum(n):
    if n >= 0:
        sum = 0
        while n:
            sum += n % 10
            n /= 10
        else:
            print sum
            return sum

Can you explain what the n /= 10 does? That totally works for the exercise but I want to know WHY it works. Or I'll never remember it, it just won't stick. Thanks!


#7

@mtf Can you explain what the n //= 10 does? That totally works for the
exercise but I want to know WHY it works. Or I'll never remember it, it
just won't stick. Thanks!
Your code:

def digit_sum(n):
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total

@turtwigpo had similar code (n /= 10) and that one works too. Know what the difference is?


#8

Adding and multiplying and then copying back into one variable increases, or augments that value.

a = a + b  =>  a increases by b

a = a * b  =>  a increases by a factor of b

a = a ** b =>  a increases by a power of b; b > 1

We can roll these operations into one statement using augmentation operators.

a += b

a *= b

a **= b

By the same token, subtracting, dividing and rooting decrease a value when the result is copied back onto itself.

a = a - b  => decreases a by b

a = a / b  => decreases a by a factor of b

a = a // b => decreases a by a factor of b, rounded down

a = a % b  => decreases a to the modulo of b

a = a ** b => decreases a by a power of b; b < 1

Again, we can role these into one simple statement

a -= b

a /= b

a //= b

a %= b

a **= b; b is a fraction, such as, 9 ** 0.5 == 3

Segue

A number divided by 10 can be a float with some decimal fraction portion. A number floor divided by 10 can be a float or an integer, but it will have no decimal fraction portion.

11.0 // 2    => 5.0

11 // 2      => 5

Python 2 treats division differently than Python 3. We are eventually going to have to migrate over to P3 so forming good habits in P2 will help adapt to the changes in 3.

Consider the following...

11 / 2        => 5 in Python 2; 5.5 in Python 3

11 / 2.0      => 5.5 in Python 2; same in Python 3

The latter is implicitly defining a float. When we see this we can't help but think, hey, cool! But it is a poor practice to get drawn into. Explicit declarations are best.

float(11 / 2)  => 5.5

int(11 / 2)    => 5

#9

Consider we are given a number, 24683579 ans we wish to add the digits using the above mathematical procedure.

24683579 % 10  => extracts the 9 which we add to the total

24683579 // 10  => 2468357

2468357 % 10  => extracts the 7, add to total

2468357 // 10  => 246835

See the pattern forming here?


#11

wow @mtf you beat me too it :grinning:


#12

def digit_sum(n):
x=str(n)
for y in x:
z=0
z=z+int(y)
return int(z)
digit_sum(4567)

Please help , whats wrong with this code ?


#13

whats wrong with this code ?

def digit_sum(n):
total=0
while n>=0:
total= total + n%10
n=n//10
return total


#14

Initialize the variable before the loop.

z  = 0
for y in x:

will set up an infinite loop. 0 // 10 is 0.

while n > 0:

#15

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