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


#21

The string conversion throws me off. I’m only doing it because the hint suggested it’s one possible path to the solution, but now I’m entrenched in doing it that way and I feel like–as Ionatan said–I’m just guessing.

Isn’t adding int_x to sum_n the object of my code? Everything before that is building up to that line of code. The way I understand it, what I need to do is take an integer, n, (let’s use the example of 1,234) iterate through each digit (1, then 2, then 3, then 4) adding them all together. What I’m trying to do is take x, which ought to be individual digits in n (e.g. 1, 2, 3, and 4) and put them into a bucket, one at a time. Then at the end, that bucket is the sum of 1+2+3+4. sum_n is my bucket–the sum of all the digits in n added up.

So (the way I understand it), x should be 1 at one moment, then the next moment it should be 2, then 3, then 4. Each of those digits, in sequence, should be piled into sum_n so that the value of sum_n should be 1, one moment, then 3 [1+2], then 7 [1+2+3], then 10 [1+2+3+4]. That isn’t happening with my code, though, for some reason. I can’t see any reason why it shouldn’t be, but it’s not.

I actually forgot that updating a variable, x += 1 is the same as saying x = x + 1.

I erased everything I had and started from scratch, but it looks like I came up with the exact same thing, only now I have the word “return” in there:

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

the output:

1

The little error at the bottom:

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

#22

It seems like x doesn’t iterate through the individual digits of n if n is not a string; it just takes the original number, n as a single unit rather than taking each constituent digit individually. I think that’s why I’m turning n into a string.
So I turn n into a string, iterate through each digit, (meaning x begins its life as a string) then convert the output stored in x into an integer and add it into sum_n. At the end, I need the sum of all the digits in n to be stored in sum_n.
Unless there’s something I’m missing, I think I know what needs to be done, I just don’t know how what needs to be done needs to be done.


#23

Guessing is okay, if it takes a form of experiment. Theory, hypothesis, trial. Record the result and analyze it. Eventually we get a handle on what happens when we do something a certain way, and with some testing will find that it always does that. This builds on our knowledge base. Don’t be afraid to try things out, but expect them to not work sometimes. Dig into the why in those cases.


#24

I’m only going to say one thing here…

Check your indenting. :slight_smile:


#25

Thank you! Oh my god. Oh my god, it’s finally over.


#26

Yeah it is.
In other words, that’s not what you are doing. Which tells you what to investigate and adjust.

Again, print out what’s being done and observe that output. That’ll tell you where/when things happen differently from what you mean. No guessing. Finding out.

What exactly would it be iterating over? There aren’t any digits. To convert to string python has to figure out the digits, that’s why conversion useful here, it does a big part of the work for you. Your summary there is correct.

The part where you observe and make sure those are really the things you’re doing. There’s no guessing here either.

Assumptions are great. As long as that’s all they are. They’re not facts, that’s the whole point, there’s a condition. Making an assumption and carrying out the rest can sometimes tell you if the assumption is wrong by causing a contradiction somewhere down the line.


#27

I want to somewhat object to playing around with indentation and accidentally getting it right though.

It’s not over until one can go through the reasoning to get there


#28

I don’t think that @thegovernment0usa was playing around with the indenting…

From their reply further up, it seems that they’re beginning to grasp what’s going on in their code. Granted, they seem a bit unsure on some points, but confidence comes from understanding and that in turn comes from repetition.

Their code, as they posted it, worked fine - aside from the return statement’s indent being wrong.

Do you understand everything on this exercise now, and why both your code block and the Codecademy solution were valid and worked? :slight_smile:


#29

On the other hand, I have no objection to changing pedagogical tactics. Especially when I’m not being very efficient. Sometimes I wonder what I’d think of myself.


#30

Randomly inserting and/or backspacing over spaces to screw around with my indenting would have been a cheap way of finding my solution, but that’s not what I did. When Thepitycoder suggested I check my indenting, I immediately saw what he was talking about and reduced the indentation before my return sum_n statement. I was being held back by a simple error. It was just a mistake–whereas earlier, when I was begging for help, I was being held back by much more serious problems.

I am very grateful for everyone’s help. I took all of your advice and it got me where I needed to go.

See you on the next one. Probably 5 of 15.


#31

That reasoning relies on already knowing the problem though.
What I’m looking for is something which takes you there.

getting wrong answer -> look at what happens -> exiting function before having finished iterating -> move return statement

Same thing as everything else really. Look at what happens. Adjust.

When I was starting out I would write some absolutely horribly complicated code for really simple tasks. It was awful. But by observing what was going on it was a simple matter to get things to connect and work in the right direction.


#32

I went back and practiced loops and I’ve arrived at this problem again. I didn’t want to solve it the way I did before, I wanted to try the “more challenging” one. At first I thought it seemed easier, because I had a sense of direction the whole time; but now I have become stumped.

Here’s what I have:

def digit_sum(n):
  bkt = 0# this is where the sum will be stored
  while len(str(n)) >= 2:# because modulo 10 doesn't seem to isolate the rightmost variable unless there are at least two digits
    bkt += (n % 10) # isolates the rightmost digit and adds it to `bkt`
    n = n // 10 # shaves off the rightmost digit so it's not present for the next iteration..
  else:# this block should only be executed if the length of str(n) is 1.
    n += bkt # this should tie the whole thing up in a neat little package with a bow on top.
  print bkt # this is the only print statement inside the function, so the console should only print one thing, one time.

print digit_sum(456) # for debugging

When I try to run digit_sum(123), this is what the console says:
image

When I try to run digit_sum(234), this is what the console says:
image

When I try to run digit_sum(345), this is what the console says:
image

When I try to run digit_sum(456), this is what the console says:
image

When it’s printing to the console, the first two lines appear immediately, then there’s a brief pause, then the next two lines appear.

Up to this point, I’ve been able to decipher what the errors and problems mean, but this one has me stumped. I don’t know why it’s printing four lines rather than one. I don’t know why it says “None” (although someone recently explained to me why Python might do that). I don’t know why it prints two lines, then pauses, then prints two more.


#33

You are using a mathematical approach so toss the str() aside. It is not needed.

total = 0
while n > 0:
    total += n % 10
    n //= 10
return total

The key is to return, not print in your function. Do the printing at the caller, only.


#34

Ohhh! I thought maybe my program was still too simple. Turns out I was over-complicating it. I was worrying about how to get the length of n but if n has no value then its “length” doesn’t matter, and I don’t have to worry about len(str()).

It was considerably less frustrating for me to do it this way. The other way, with string conversion and all that, was much more elaborate and difficult to nail down. I guess this one is considered “more challenging” because it requires a bit of Googling, beforehand.

As always, thank you for the quick response and thank you for the insight!

PS I appreciate that you spoiler alerted the solution in your reply.