Difficulty with 4/15


#1

So I've been scratching my head over 4/15, and I need some assistance in figuring out where the problem areas in my code are.

def digit_sum(n):
n = str(n)
awnser = 0
count = 0
temp = []
for item in range(0,len(n)):
temp = n[:count]
awnser= int(temp)+awnser
str(temp)
count = count+1
print awnser

what this is supposed to do is turn n into a string, cut it at the current stage of the for loop which continues for as long as the string is, then before adding it to the awnser variable, turns it back into an integer so that it behaves as a number. The message I keep getting is " Your code looks a bit off--it threw a "invalid literal for int() with base 10: ''" error."

please assist.


#2

def digit_sum(n):
lst = []
n = str(n)
for char in n:
lst.append(char)

total = 0
for i in range(len(lst)):
    lst[i] = int(lst[i])
    total += lst[i]

return total

The code above worked fine for me.


#3

some of your code is redundant, and can be omitted:

> def digit_sum(n):
>     lst = []
>     n = str(n)
>     for char in n:
>         lst.append(char)

so far so good.
now for cleaning up a bit.

>     total = 0
>     for i in lst:                         # No range is needed, as this will only iterate for each *i* in *lst* 
>         total += int(i)                 # Do not need to mention *lst* again, as we are only dealing with *i* (see line above)

>     return total

nothing wrong with your code. just a bit messy, and bits which don't do anything in this scenario.
but overall, thankyou. it helped me a great deal.


#4

I tried doing the mod version

from math import floor
def digit_sum(n):
number=n
total=0
for i in range(len(str(n))):
number1=number %10
total=total+number1
number=floor(number/10)
return total


#5

Whats wrong with this code

def digit_sum(z):
    n = str(raw_input("enter number: "))
    for char in n:
        z += int(char)
    return z
    

print digit_sum(z)

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

But in interpreter window it is fine:

enter number:  434
11
None

#6

I would guess it is because of the raw_input which is not wanted in this exercise.
the testing software will provide its own numbers.
see my explanation above for how to write the code.
feel free to ask questions. (someone will answer them)