2

My original python program used string interpolation to take a number a user enters between 0-9999 like 2928, and summed its individual digits (2+9+2+8=21), and then split the number until eventually it became a single digit number (in this case 3), which was displayed on the screen. The code looks like this:

Now I am needing to figure out a way to do the same without using string interpolation(converting the integers to strings and then splitting the strings, reconverting them to integers, and summing them). I am fairly new to python and therefore can use very simple commands (most complex being the while loop) can anyone help me out/ throw me some ideas?

*ps, I guess some ambiguity exists as to what yearint- year is. "year" is a command that i didnt write above but its code makes the user enter a number between 0-9999. I changed its variable name to "yearint" because I am new to python and want to make things descriptive so I can remember them when I look back. SO basically year/yearint are the input the user inputs.

2
  • 3
    None of that is actually "string interpolation". Commented Oct 16, 2012 at 3:19
  • 1
    awesome, now its obvious im a complete newb Commented Oct 16, 2012 at 3:46

4 Answers 4

6

Take the modulus by 9, with some tweaking to account for multiples of 9.

>>> (123 - 1) % 9 + 1
6
Sign up to request clarification or add additional context in comments.

5 Comments

if the number is divisible by 9 then this method does not work, ex 81, or 9999.
oh woow, how did you even come up with that?, I wouldn't even know what train of thought to follow to arrive at that. your logic is superb.<this is a legitimate questions btw, if you could possibly answer it....
You need to "rotate" the result of the modulus forwards by 1 (i.e. 8 -> 8, 0 -> 9, 1 -> 1), so you take the modulus of 1 less, and add 1 to it.
We are rotating the "0" result to become "9".
ookay I understand now, and I also see that the +1 is used to restore, or negate the effects of the -1, so that the answer given is an appropriate division/modulo by 9. Thank you very much.
1
def sumnum(num):
    if num < 10:
        return num
    return sumnum((num % 10) + sumnum(num/10))

sumnum(1234)

Because recursion. That's why.

Comments

0

I am typing this on a mobile phone, so I will use " y " instead of " yearString ".

if len(y) == 4:
    x = int(y[3]) + int([2]) + int(y[1]) + int([0])
    y = str(x)

if len(y) == 3:
    x = int([2]) + int(y[1]) + int([0])
    y = str(x)

if len(y) == 2:
    x = int(y[1]) + int([0])
    y = str(x) 

answer = int(y) 

See how, if the sum has multiple digits, a later if statement will handle it. Now let's write similar code using pure math:

x = int(yearString) 

d3 = x // 1000
x %= 1000

d2 = x // 100
x %= 100

d1 = x // 10
d0 = x % 10

answer = d3 + d2 + d1 + d0

EDIT: Now that I have thought about it, I think I see the best way for you to do this. I will not write the full code for this.

If you use the modulus operator by 10 you pull out the bottom digit. Then if you use integer division by 10, you remove the bottom digit. Do this in a while loop and keep doing it until you have all the digits out; the number will be zero after the last divide by 10. Make a function that does this, and call it from a while loop until the sum is less than 10 (is a single digit).

EDIT: Okay, I guess I might as well write the full code:

y = int(yearString)
x = 0  # we will accumulate the sum in x
while y != 0:
    x += y % 10  # add one digit
    y //= 10  # discard one digit
    if y == 0 and x > 10:
        # We have pulled out all the digits from y, but x has
        # multiple digits.  Start over so we can sum the digits
        # from x.
        y = x
        x = 0

answer = x

1 Comment

converting to strings and then to integers or visa versa is forbidden for me. Thanks for taking time typing the above on your cell. It is most appreciated. I also cant use the "len" command if it exists...
0

In Python, you can loop on a string value and you get successive characters from the string.

 for ch in "1234":
    print (ch) 

So here is the best way to sum the digit values of a string :

sum(int(ch) for ch in s)

Here we call the sum() function with a "generator expression" that gets one character at a time and converts it to an integer value. Note that when you do it this way, it doesn't matter how long the string was.

3 Comments

I cant use "ch" or "in" or "for"
Thanks, this can be used further on but the instructor limits us from using ch, or in...
In this example, ch is a variable name. There is no standard function called ch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.