473,699 Members | 2,131 Online

# getting the sum of digits in a number

16 New Member
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 15588
DDCane
16 New Member
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 Recognized Expert Expert
<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 Recognized Expert Expert
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 Recognized Expert Expert
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 Recognized Expert Expert
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 Recognized Expert Moderator Specialist
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(1234 5)
15
>>> tvarsumman(9876 54321)
45
>>> tvarsumman(1013 5)
10
>>>
Oct 26 '07 #7
Smygis
126 New Member
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 Recognized Expert Expert
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 New Member
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

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

### Similar topics

 1 2318 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 1611 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 10242 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 @@Identity"; // the auto-number fiels int iId = (int)myCommand.ExecuteScalar(); 0 1383 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 javascript. I attempt to get the client ID of the TextBox (with provided ID of that TextBox as "ext_desc") by the following code inside the Page_Load() event of the UserControl (named Color_Control): for(int i = 0; i < DataGrid1.Items.Count;... 4 2307 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 938 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 the datagrid..for example as follows: ItemNumber ItemName Qty 1111111 Apple 2 0 1277 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 1076 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 5025 by: Gangreen | last post by: Visual Basic.net : is there a way of getting the number of threads? 6 2277 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 size of the files if it is better to do so. So the idea is to search through a string and find repeats of any 3 or 4 word group. So if the author has repeated the phrase "then I went" 6 times in the text, then this would be found and... 0 8706 by: marktang | last post by: ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of... 0 8630 by: Hystou | last post by: Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,... 1 8944 by: Hystou | last post by: Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,... 0 8899 by: tracyyun | last post by: Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some... 0 5889 by: conductexam | last post by: I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();... 0 4391 by: TSSRALBI | last post by: Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls... 0 4638 by: adsilva | last post by: A Windows Forms form does not have the event Unload, like VB6. What one acts like? 1 3075 by: 6302768590 | last post by: Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system 2 2364 by: muto222 | last post by: How can i add a mobile payment intergratation into php mysql website.

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.