473,287 Members | 1,581 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

getting the sum of digits in a number

16
i made it like this:
Expand|Select|Wrap|Line Numbers
  1. def tvarsumman(n):
  2.     if n<10:
  3.         print n
  4.     else:
  5.         tvarsumman((n/10) + n%10)
but when it comes to 99 it does this

99--> 9+9=18-->1+8=9

thats wrong according to my professor.

can u help fix my function?

and all the ones u have made so far have been perfect! u are really helping me. thank u sir! :P
Oct 25 '07 #1
11 15541
DDCane
16
one other small problem i have is i need to define a function that takes the number i put in splits it up and adds them together for example:

123 --> 1+2+3=6
88 --> 8+8=16

thanks for all ur help guys u are really saving my life!
Oct 25 '07 #2
bartonc
6,596 Expert 4TB
<snip>and one other small problem i have is i need to define a function that takes the number i put in splits it up and adds them together for example:

123 --> 1+2+3=6
88 --> 8+8=16

thanks for all ur help guys u are really saving my life!
Last things first (by the way, where my dict functions helpful?):
Expand|Select|Wrap|Line Numbers
  1. >>> user_input = '12345'
  2. >>> numList = list(user_input)
  3. >>> total = 0
  4. >>> for num in numList:
  5. ...     try:  # prevent errors in the input from breaking the loop
  6. ...         total += int(num)
  7. ...     except (ValueError, TypeError):
  8. ...         pass  # do nothing
  9. ...     
  10. >>> print total
  11. 15
  12. >>> 
Oct 25 '07 #3
bartonc
6,596 Expert 4TB
i made it like this:
Expand|Select|Wrap|Line Numbers
  1. def tvarsumman(n):
  2.     if n<10:
  3.         print n
  4.     else:
  5.         tvarsumman((n/10) + n%10)
but when it comes to 99 it does this

99--> 9+9=18-->1+8=9

thats wrong according to my professor.

can u help fix my function?

and all the ones u have made so far have been perfect! u are really helping me. thank u sir! :P
You are welcome. I would not have guessed that English was not your first language. However, I am having some trouble following this.
Oct 26 '07 #4
bartonc
6,596 Expert 4TB
You are welcome. I would not have guessed that English was not your first language. However, I am having some trouble following this.
If recursion is not a requirement, then this may be what you are looking for:
Expand|Select|Wrap|Line Numbers
  1. >>> def SumDigits(n):
  2. ...     numList = list(str(n))
  3. ...     total = sum(int(c) for c in numList)
  4. ...     print total
  5. ...     
  6. >>> SumDigits(99)
  7. 18
  8. >>> 
Oct 26 '07 #5
bartonc
6,596 Expert 4TB
i made it like this:
Expand|Select|Wrap|Line Numbers
  1. def tvarsumman(n):
  2.     if n<10:
  3.         print n
  4.     else:
  5.         tvarsumman((n/10) + n%10)
but when it comes to 99 it does this

99--> 9+9=18-->1+8=9

thats wrong according to my professor.

can u help fix my function?

and all the ones u have made so far have been perfect! u are really helping me. thank u sir! :P
Expand|Select|Wrap|Line Numbers
  1. >>> def tvarsumman(n):
  2. ...     total = 0
  3. ...     while n > 0:
  4. ...         total += n%10
  5. ...         n /= 10
  6. ...     return total
  7. ...     
  8. >>> print tvarsumman(99)
  9. 18
  10. >>> print tvarsumman(123)
  11. 6
  12. >>> 
Oct 26 '07 #6
bvdet
2,851 Expert Mod 2GB
i made it like this:
Expand|Select|Wrap|Line Numbers
  1. def tvarsumman(n):
  2.     if n<10:
  3.         print n
  4.     else:
  5.         tvarsumman((n/10) + n%10)
but when it comes to 99 it does this

99--> 9+9=18-->1+8=9

thats wrong according to my professor.

can u help fix my function?

and all the ones u have made so far have been perfect! u are really helping me. thank u sir! :P
Using recursion, you need a way to terminate the function. You can do that by substituting 'print n' with 'return n'. The last line also needs a return, and n%10 needs to be outside of the argument list. Use divmod() to determine the integer quotient and remainder.
Expand|Select|Wrap|Line Numbers
  1. def tvarsumman(n):
  2.     if n < 10:
  3.         return n
  4.     else:
  5.         n, rem = divmod(n, 10)
  6.         return tvarsumman(n) + rem
Example:

>>> tvarsumman(99)
18
>>> tvarsumman(12345)
15
>>> tvarsumman(987654321)
45
>>> tvarsumman(10135)
10
>>>
Oct 26 '07 #7
Smygis
126 100+
Tjo! Gissar att du är svensk ;)
Och att du ska räkna ut tvärsumman med hjälp av en rekursiv funktion.

(Sorry about the language everyone else. And DDCane to if im wrong about his nationality, nothing realy important above)

Anyway:
Expand|Select|Wrap|Line Numbers
  1. def numsum(n):
  2.     if n > 0:
  3.         n = n % 10 + numsum(n/10)
  4.     return n
  5.  
Something like that?
Oct 26 '07 #8
bartonc
6,596 Expert 4TB
Tjo! Gissar att du är svensk ;)
Och att du ska räkna ut tvärsumman med hjälp av en rekursiv funktion.
Two Swedes on the boards! Very cool. My father was half Swedish, but I never learned the language.

(My apologies if I have mistaken your nationality)
Oct 26 '07 #9
Smygis
126 100+
Two Swedes on the boards! Very cool. My father was half Swedish, but I never learned the language.

(My apologies if I have mistaken your nationality)

Nope, Youre entirely correct. I'm from Sweden.
I klicked report insted of reply :/ meh.
Oct 26 '07 #10
DDCane
16
Nope, Youre entirely correct. I'm from Sweden.
I klicked report insted of reply :/ meh.
Hey guys! Actually I'm American but I live in Sweden at the moment. Where in Sweden are from?
Oct 27 '07 #11
Smygis
126 100+
Hey guys! Actually I'm American but I live in Sweden at the moment. Where in Sweden are from?
Up in the north. Live somewhere in the area around Umeå now.
Oct 27 '07 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Spidah | last post by:
Is there an easier way to get the number of items in a database table than selecting all the records in it and then running mysql_num_rows on the result? Hamilton www.laughland.biz
5
by: ssmith579 | last post by:
I'm trying to extract single digit number from a string. t = '06897' I want to get the 7, 9,8 & 6 seperated out to use but can't find a way to split out the single characters. Thanks
4
by: Shahar | last post by:
Hi I need to get a field name 'ID'(that is an auto-number field) right after I add a new row to table, it's work like that: myCommand.ExecuteNonQuery(); myCommand.CommandText = "SELECT...
0
by: John Shum | last post by:
I prepare a UserControl that act as a lookup control, once the code is enter in the TextBox, the description will appear in another TextBox outside the UserControl of the same row in a DataGrid via...
4
by: UJ | last post by:
Is there a way to get the number of items that are in an enum? I'm trying to find out how many items there are so that I can hit every one of them to test. TIA - Jeff.
1
by: amiga500 | last post by:
Hello, I have a data grid which can contain as many items as possible in one of the columns I have Qty. What I want to do is when I run the forum I want to get the number of items available in...
0
by: FORGET | last post by:
Can anybody show me how to get the serial number of a pocketpc using VC++? I can get the PDA name with RegQueryValueEx, but I have no idea what to send for the serial number. Thanks
0
by: StanislavPetrov | last post by:
How to get the number of the current line in a RichTexBox?I mean the line under the mouse cursor.
6
by: Gangreen | last post by:
Visual Basic.net : is there a way of getting the number of threads?
6
by: jeddiki | last post by:
I am writing a little script that will improve authors writing skills by finding repeated phrases in the text. The text of a chapter will average about 10,000 words, however, I could reduce the...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.