How can I break down these problems into easier parts?


How can I break down these problems into easier parts?


This is a key part of problem solving in programming, so be on the lookout for hints about how to break down the problem when going through the instructions. In the digit_sum exercise, we know a few things:

  1. Our function takes some positive integer n as input.
  2. If we convert that input to a string using the built-in str() function, we can iterate through it using a for each loop to get each “character” (digit) in the string.
  3. We can do something with each digit inside of that for each loop.
  4. We must return the result at the end, not inside of the loop.

2 posts were split to a new topic: Explain why my code wouldn’t be a solution to this exercise?

A post was split to a new topic: Provided digit sum solution is confusing


Could you review my code below:

> def digit_sum(x):
>     n = len(str(int(x)))
>     t = 1
>     a = 0
>     while n - t >= 0:
>         a += int(x / (10 ** (n - t)))
>         t += 1
>     return a

When I test the code with x=123, which is:

print digit_sum(123)

It gives me 136 instead of 6. Any idea??? Thank you!!

Let’s rule out what we cannot do, then work toward what we can do…

Can we iterate over an integer?

>>> for x in 123456789:
	print (x)

Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    for x in 123456789:
TypeError: 'int' object is not iterable

That rules out being able to simply add the digits in a loop. But does it, really?

>>> for x in str(123456789):
	print (x)


Now we have a basis for iteration, and we know how to keep a running sum… a = a + x. However since x is a string, we will hit a snag…

>>> total = 0
>>> for x in str(123456789):
    total += x

Traceback (most recent call last):
  File "<pyshell#36>", line 2, in <module>
    total += x
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

No problem, since we know about the str() constructor, we must know about the int() constructor, too.

>>> total = 0
>>> for x in str(123456789):
    total += int(x)

>>> print (total)

So we used three operators, =, in, and +=; one loop, for, and two built-in’s, str(), and int(). This is the simplest approach to this problem using basic arithmetic.

The less naive approach uses maths, but very few learners will arive at this one, since some concepts are still pretty new, if not completely foreign.

//           =>  floor division
%            =>  modulo (remainder)

Modulo will give us the last digit if our divisor (modulus) is 10…

123 % 10     =>  3

Floor division will reduce it by one digit if we divide by 10…

123 // 10    =>  12

So now we set up a loop to carry out the cycles until we reduce the number down to zero…

>>> total = 0
>>> x = 123456789
>>> while x > 0:
    total += x % 10
    x //= 10

>>> print (total)

Now we get to your method, that of progressively decreasing by powers of 10 and dividing. Something to consider,

n = len(str(int(x)))

x is already stipulated to be an integer so the int() function is not needed. We can however make use of the length, as you have deduced.

>>> total = 0
>>> x = 123456789
>>> for n in range(len(str(x)) - 1, -1, -1):
    y = x // 10 ** n
    total += y
    x -= y * 10 ** n

>>> print (total)

We’ve seen how the solutions have grown in complexity and one must ask, which of these is the simplest?

def digit_sum(n):
  // create two variables: first to store the numbers as string and the other to store the overall total
  to_string = str(n)
  total = 0
  // loop through the string, convert it to an int and store it in the total
  for s in to_string:
    total += int(s)

  // return the total  
  return total 

print digit_sum(1234)

Any idea what the problem is here? I just tried the mathsy method:

def digit_sum(n):
  n = str(n)
  total = 0
  for digit in n:
    q = int(n) % 10
    total += q
    q //= 10
    return total
print digit_sum(6061)

I just tried doing the 3 backdashes before and after this post, and it still won’t convert to code format…

if you try the mathsy method, why would you convert to string?

To be able to iterate through all of the items in the number, right?

No, the mathsy approach allows us to work with the integer.

lets say we need the digit sum of 123456, we can get the last digit by using the modulo operator. then to remove the last digit, we can divide by 10. one hundred and twenty-three thousand, four hundred and fifty-six (123, 456) divided by ten and rounded down is twelve thousand, three hundred forty-five (12, 345). We have successfully removed the the last digit.

now we can extract the 5 (new last digit) using the modulo operator and so forth.

the whole point of this approach is to avoid using strings. My question was intended as such :wink:

1 Like

I have just started learning Python and was not aware of floor division hence used my own approach to get the sum of digits

def digit_sum(n):
total = 0
q = n/10
r = n%10
print “Input Number is : %s” %n
while r > 0:
print “remainder : %s” %r
print “Number is : %s” %q
total += r
r = q % 10
q = q/10
return total

print “Sum of Digits is: %s” %digit_sum(123456)

In Python 2 the above is integer division, so floor division is not required since the quotint is an int. In Python 3 we either have to use floor division or invoke the int() constructor on the quotient so we don’t get a float.

15 / 10   =>  1.5
1.5 % 10  =>  1.5
1 Like

def digit_sum(n):
a = str(n)
total = 0
if n > 0:
for b in a:
total += int(b)
return total
print total


How to call the function here? and is this alright?

close, the function has a parameter (n), so you need to provide an argument at function call


def digit_sum(n):
val = str(n)
count = len(val)
total = 0
while count > 0:
total += int(val[count-1])
count -= 1
return total

print digit_sum(434434)

any potential problems here? works for me:

def digit_sum(n):
  text = str(n)
  summe = 0
  for i in text:
    summe += int(i)
  return summe

def digit_sum(n):
for number in str(n):
int(number) = int(number) + int(number)
return number

print digit_sum(1234)

Getting " File “python”, line 3
SyntaxError: can’t assign to function call"

What does it mean?


int(number) =

you try to assign to function call, but you can not assign to function call (int() is a function call)

Thanks. Then how am I supposed to use int to do the addition?