4/15 - "digit_sum" - Don't know how to start and the hint only confused me more


#1

Instructions:

Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number’s digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that the number you are given will always be positive.)

Check the hint if you need help!

So here’s what I have:

def digit_sum(n):
  sum(n)

Obviously I’m missing something. I also tried:

def digit_sum(n):
  for x in n:

…but then I ran out of ideas.
The hint tells me to convert something into a string… but I can’t wrap my head around why I’d do that; this is arithmetic.

Hint:

One way might be to convert the integer to a string with str(), iterate over it, and turn the substrings back into integers with int() to do the addition.

If you’re looking for a challenge, try this: to get the rightmost digit of a number, you can modulo (%) the number by 10. To remove the rightmost digit you can floor divide (//) the number by 10. (Don’t worry if you’re not familiar with floor division—you can look up the documentation here. Remember, this is a challenge!)

Try working this into a pattern to isolate all of the digits and add them to a total.

What is a substring? I tried Googling it but didn’t understand the result.

Edit: I just realized I’m supposed to sum the digits of a number! To use the program’s example, it’s not [1,2,3,4], it’s one thousand two hundred thirty-four.


Digit_sum - 4/15 - still lost
#2

yea, getting the sum of digits (integer) or a list does really matter. Does it make sense now?


#3

That at least helped me to get started but I have been throwing myself against a brick wall for hours and I am completely stumped. I keep getting the same error.
When I do this:

def digit_sum(n):
  sum_n = 0
  for str(x) in range(str(n) + 1):
    str(x) += sum_n
    print sum_n
    
print digit_sum(1234)

…I get this error:

  File "python", line 3
SyntaxError: can't assign to function call

When I do this:

def digit_sum(n):
  sum_n = 0
  str_n = str(n)
  for x in str_n:
    range(str_n + 1) += sum_n
    print sum_n
    
print digit_sum(1234)

…I get this:

  File "python", line 5
SyntaxError: can't assign to function call

When I do this:

def digit_sum(n):
  sum_n = 0
  str_n = str(n)
  for x in str_n:
    int(range(str_n + 1)) += sum_n

I get this:

  File "python", line 5
SyntaxError: can't assign to function call

When I don’t get that error, I get “cannot concatenate string and int objects” or something like that. I haven’t seen that error in a while, but it seemed to be happening when I had painstakingly made certain every string was turned back into an integer.

Note: the print digit_sum(1234) part is for debugging, but not once has it printed. A few times I got an infinite recursion column of zeroes and I don’t know why, but that hasn’t happened in over an hour.

I’ve spent every free moment of the past five and a half hours doing this and it’s costing me my sanity.


#4

You’re writing things that make no sense whatsoever. Use what you know is possible to do.


#5

this is good:

def digit_sum(n):
  sum_n = 0
  str_n = str(n)
  for x in str_n:

now all you need to do is add x (which will contain the digits) to whatever variable use to count.

I agree with ionatan, some of those code samples are confusing and make very little sense. There is no shame in check documentation or reflecting on earlier lessons


#6

It’s like building with lego. You’ve got a vision for what that lego house is supposed to look like, and you use the lego bricks you have available to fill that out.

You’ve got operations like converting back and forth, calling functions, looping, variables, arithmetics.
Use them. They’re all you need and you should know perfectly well how they are used. And if you’re not writing them correctly, go back and experiment with how to write those things in separate (new file) much simpler examples, and then apply those actions to the code you’re currently writing.

Start by thinking through in detail what actions need to happen. Write it down. In English. Follow the instructions you just wrote, do they do the right thing? Translate to code, one action at a time.


#7

If this doesn’t make sense then I am completely lost and have to discard the last six hours of work.
The hint tells me to turn something into a string and then back into an integer for some reason. I figure it’s so I can use the index, which is why I’m using range(). I can’t think of any other way to make it take each individual digit in a whole number, do something to it, and put it in a bucket. However, that isn’t working.
I actually did make a list of the things I need to do. I had it in a comment above where I was working my code so I could easily refer back to it. Here’s that comment:

"""
Okay.  So I will probably have to define at least one variable... right now I'm thinking it'll probably be *only* one.
I may also want to use a WHILE loop--something like 'while there are still digits to go, keep taking them and putting them in this bucket.'
Maybe .append() could be useful?
Surely I can use the index without converting it to a string?
Maybe len() will come in handy.
Maybe some kind of 1%s%s where %s is like += 1, so it counts up as long as there are units left in the index?
range(n+1) - range(stop) goes up to but not including 'stop'
1. define function
2. turn n into a string
3. add integer versions of everything in n to another variable
4. print that variable
"""

I walked through those steps one by one and arrived at the code I posted above.


#8

but if we look at your code:

def digit_sum(n):
  sum_n = 0
  str_n = str(n)
  for x in str_n:
     print x

digit_sum(434)

we see that x contains the digits, so we only have to add x to sum_n (assuming you want to store the sum there), but we do have to convert x to int(), why you considered range(), .append() or len() i am not sure


Digit_sum - 4/15 - still lost
#9

Some things are indeed completely out of the blue. You need to move between certainties.
You’re the one making things fit together. If you guess, then nobody is arranging things and there’s no reason why it would work. There can’t be any part where you suddenly start guessing without noticing. So it all has to be built on what you know you can do. Everything has to be argued for.

And the things used are such that you can move between certainties. Basic operations you should know how to use, and what they do. A task which you can carry out manually and therefore know what steps are involved. Break the task down into steps you know how to write, write it, and you’re done.


#10

That’s the problem: I don’t even know where to start. I thought I had myself pointed in a direction, but I’ve just come to find out I’ve been spinning in circles.
I considered len() and range() because they are two things that work with the index. Since I don’t know what actual number n will be, I have to do algebra with the index and things like len() and range() are how you do that. Right?


#11

why would we need indexes? Seems you need to refresh your knowledge on for loop and strings

have you ran the code i gave you @thegovernment0usa? Did you see what it did?


#12

No, their positions are of no concern if you’re already visiting each one, so where does that idea come from? <---- this is what you have to detect and eliminate in your reasoning

You don’t need any technical input here. You know all of that. You’re leaving the realm of what you know and you can’t let yourself.

You assume that you need len/range. But you don’t have an argument for it. Go back to what you can argue for, and ask yourself what you need from there. Refer to how you’d do it manually - because you already know how to carry out the task and therefore have something to observe to find out what to do next.

Refer to your list of instructions. It’s like a checklist. How far have you come in that, have you got everything you wanted so far, and what is the next thing? That’s where you start each time you don’t know what to do next. You refer to what you would do manually, that’s your guide.


#13

Also, mind you, I’m not saying you need to do anything any particular way.
It’s all just an argument for that you have everything you need all the way through.

But yes, you do have to eliminate the guesswork.


#14

You haven’t decided what should happen yet.
Decide. Then stick with it. A programming language doesn’t do these decisions for you. Decide, and then describe in the language what you decided.

Pen and paper. Go through the process manually a bunch of times. Observe what you do. Allow yourself to recognize the operations you know how to describe.

Don’t make large mental leaps. Turn it into steps you could tell a five-year-old to carry out.


#15

Numbers cannot be iterated, but strings can. String characters of numbers cannot be added, only concatenated so each character needs to be turned back into a number so we can add it to the accumulating total.


#16

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


#17

#18

My last thread closed due to inactivity.
I took a week off from this because it was so discouraging for such an apparently simple exercise to be so baffling.

From my last thread:

I tried following that advice:

def digit_sum(n):
  sum_n = 0
  str_n = str(n)
  for x in str_n:
    int_x = int(x)
    int_x += sum_n
  print sum_n
    
print digit_sum(1234)
#str_n = "1234"
#int_n = 1234

…and at least I stopped getting that “line 5, can’t assign to function call” error, but now I get:

0
None
0
0

and at the bottom, it says:

Your function fails on digit_sum(434). It returns None when it should return 11.

I feel completely lost. How is this one so hard if everybody thinks it’s so simple? Ionatan suggested I didn’t need any technical help–that I already know everything I need to know to do this, but I don’t have a single thought in my head that points me in any direction (let alone the right one).

Update: I broke down and clicked the “solution” button and–what is this?

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

This… what? I mean–I can’t even–I wasn’t even a tiny bit close. I’m over here assigning variables and switching things back and forth from integers to strings (for reasons I don’t understand) and the solution is over here using greater-than and modulo and this double-slash thing, whatever that is. It looks like they said a thing equals itself divided by ten? What?

Am I exceptionally bad at this? Do other people struggle this much?

I’d still like to solve this exercise before I proceed. Seeing the solution only made me feel more lost. Any advice would be appreciated.


#19

everything you need here has been taught, but the trick is too align everything to get to the solution.

i think here you are getting pretty close:

def digit_sum(n):
  sum_n = 0
  str_n = str(n)
  for x in str_n:
    int_x = int(x)
    int_x += sum_n
  print sum_n
    
print digit_sum(1234)

look at this code:

int_x += sum_n
# lets remove shorthand:
int_x = int_x + sum_n

both lines of code are the same. Why would you want to add sum_n to int_x? we want to add the integers to the sum, and then return the sum

there are multiple ways to solve this problem, i would go with what you where trying. The suggested solution although more efficient (integers only, no string conversion) its also more complicated

no, a lot of people struggle here. This takes programming to the next level (coming up with solutions)


#20

Then don’t do it.

Here’s what I see. Let’s say you’re at the pub throwing darts.
“I don’t know why I’m throwing in this direction, and I don’t know why I’m not hitting the target”

Then don’t throw. Find out where the target is and throw in that direction.

“I don’t know why I’m converting these ways, and I don’t know why the result isn’t the sum of the digits”

You have to make it so. Nothing about python will make anything you write snap into place, similar to how a throwing dart isn’t a laser guided missile. You have to make it so. Don’t do any converting that you don’t understand. Do only what you understand, consider the situation, ask yourself what you need next. Then you do that, or you learn how to do that, and then do it.
When you miss the target with your dart, find out where the dart hit and then adjust accordingly, a bit more to the left perhaps. If you print out zero then you didn’t add. If you had each digit (found out by printing) then whatever you did to add was not effective. Investigate how to add. Adjust.

The task itself is incredibly simple. It’s your method of solving that needs work, so that you can take on bigger tasks. It’s not the task you’re struggling with. There’s not much to struggle with there. The problem is that you entirely skip the aiming part of your dart, not that hitting the bulls-eye is difficult.
The method you need to be following is to repeatedly consider the current situation (which you have to understand to continue) and then apply further steps (which you also have to understand to understand next situation)

The suggested solution should also be entirely readable to you. And I suspect it is, but that you’re not actually considering how the current state of the program is affected while carrying those things out. You should probably grab pen and paper and carry it out. If there’s something you don’t understand (should really only be //) then there’s google for that, and then you can continue. It’s not something to be stared down and understood. That’s not what anybody does to understand code except Chuck Norris:

Chuck Norris doesn’t read books. He stares them down until he gets the information he wants.