# Help with building code without the string format

#1

this code says memory error for this line 'i.append(int(y)). I want to solve the code using this format and not the string format

I am not expecting any errors

``````def digit_sum(n):
n = abs(n)
x = 0
a = 10**x
b = n/a
l = []
while b >= 0.1:
y = n%a
y = y*10
l.append(int(y))
x += 1
return sum(l)``````

#2

`a` is set to `1`, then `n/a` equals `n`. `b` never changes. This results in an infinite loop.

Let's pencil through the code and see what is happening...

``n = abs(n)``

So, `n` will be greater than zero if it is not already zero. Let's review this edge case, `n == 0`

``````x = 0
a = 10 ** x   # 10 ** 0 is 1 so a == 1
b = n/a       # 0 / 1 == 0``````

Since b is 0, it does not enter the while loop.

``sum([])       # 0``

No errors. That's good. Now let's set `n` to `434`

``````n = abs(n)       # 434
x = 0
a = 10 ** x      # 1
b =  n / a       # 434
l = []           # `l` is a poor choice for variable (looks like 1)

while b >= 0.1:
y = n % a    # 434 % 1 == 0
y = y * 10   # 0 * 10 == 0
l.append(int(y))
x += 1``````

See anything weird going on here? The list is appended indefinitely, each new element is a zero. Python runs out of memory.

#3

Thank you, what do you suggest I do to make b change its value for every increment in x?

#4

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