Python 15.4:Practice Makes Perfect


Good Morning Friends, I have doubts about a code/solution for:

Can any body please explain how does this code works

The comments are reflect my understanding of code

def digit_sum(n):
#Turn the given number sequence into string
    a = str(n)
#Create an empty list for holding looped string
    b = []
#looping through the string and then appending each element to list"b"
    for i in a:
    b = [int(i) for i in b]
    c = sum(b) 
    return c

print digit_sum(56796144687)

I am specially confused by this line

b = [int(i) for i in b]

Thanks for your effort


It works by changing the i which were appended to b to integers for calculation, since it was previously set to a string.

Your code could also be simplified as:

def digit_sum(n):
    n = str(n)
    total = 0
    for c in n:
        total += int(c)
    return total
print digit_sum(56796144687)


Thanks for explanation, I was already thinking along similar lines to your code.


I f you care to look my code for
The following are two different approaches to solution the first one works

def factorial(x):
    for i in range (x):
    return fact

print factorial(11)

The second one doesn't

def factorial(x):
    if x==1:
        return x
        return x*(x-1)
print factorial(11)

Could you maybe solve challenge without "for" loop


Yes, you could import the functions from math:

from math import factorial
def factorial(x):
    return math.factorial(x)


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