## Sum of the digits in a number (python)

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

kernelpanic
Posts: 891
Joined: Tue Oct 28, 2008 1:26 am UTC
Location: 1.6180339x10^18 attoparsecs from Earth

### Sum of the digits in a number (python)

Well, basically, the title says what I'm trying to do. For example, take 468187041. The answer is 4+6+8+1+8+7+0+4+1=39. I've got no idea how to do this. I've seen some people use a function called reduce, but the interpreter doesn't recognize it, so if you could help me without using that, please do. Oh, I'm using python 3.0. Thanks!
I'm not disorganized. My room has a high entropy.
Bhelliom wrote:Don't forget that the cat probably knows EXACTLY what it is doing is is most likely just screwing with you. You know, for CAT SCIENCE!

Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

### Re: Sum of the digits in a number (python)

In python 3 you need to import functools to get reduce. Anyway, reduce won't help much here, since the function argument needs to return something of the same type as the input values (in this case a string). You could do it by converting to and from strings, but it's better to just use a for loop (the intention behind moving reduce out of the builtins), or define a proper fold function:

Code: Select all

`def fold(func, init, seq):  """ A proper reduce function. Takes the reducing function, the initial value and the sequence to fold. """  for elem in seq:    init = func(init, elem)  return init`

Note that reduce is a specialized version of this, and could be defined (modulo the fact that not all sequences are indexable...)

Code: Select all

`def reduce(func, seq):  if len(seq) == 1:    return seq[0]  return fold(func, seq[0], seq[1:])`

Note that reduce fails on empty sequences, while fold returns the 'init' argument in that case.

Also, int() converts a string to an int, and a string consists of strings of length one...
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: Sum of the digits in a number (python)

Code: Select all

`sum(map(int,str(12345678)))`

Convert number to string
Convert each character to int
Sum the list of ints

Guff
Posts: 165
Joined: Thu Jan 03, 2008 11:56 pm UTC

### Re: Sum of the digits in a number (python)

Alternatively, for the sake of boredom you can do it without conversion to a string through the use of modulo and integer division:

Code: Select all

`def sum_digits(n):   import math   total = 0   for i in range(int(math.log10(n)) + 1):      total += n % 10      n //= 10   return total`

Even still, for the sake of obfuscation it can also be written as:

Code: Select all

`sum_digits = lambda n: sum(n//(10**i) % 10 for i in range(int(math.log10(n)) + 1))`

Granted, I'm pretty sure for very large numbers it will be less efficient than a conversion to a string, but I guarantee you will pick up chicks with this method.

sparkyb
Posts: 1091
Joined: Thu Sep 06, 2007 7:30 pm UTC
Location: Camberville proper!
Contact:

### Re: Sum of the digits in a number (python)

Berengal wrote:Anyway, reduce won't help much here, since the function argument needs to return something of the same type as the input values (in this case a string).
...
or define a proper fold function:
...
Note that reduce is a specialized version of this

Um, I have to correct you here. reduce is a proper fold function. Except that it's argument are in a different order (func, seq, init) with the init argument being optional. Only when you leave out the init argument does it try to use the first element of the sequence instead. So you could certainly do:

Code: Select all

`reduce(lambda sum,digit: sum+int(digit),str(number),0)`

although I liked 0xBADFEED's solution to map all the digits to ints first and use the sum function (which is a special case of reduce where the function is addition and the initial element is 0).

kernelpanic
Posts: 891
Joined: Tue Oct 28, 2008 1:26 am UTC
Location: 1.6180339x10^18 attoparsecs from Earth

### Re: Sum of the digits in a number (python)

Guff wrote:Alternatively, for the sake of boredom you can do it without conversion to a string through the use of modulo and integer division:

Code: Select all

`def sum_digits(n):   import math   total = 0   for i in range(int(math.log10(n)) + 1):      total += n % 10      n //= 10   return total`

Actually, that's the best I've seen (I strongly dislike strings) Thank you to you and everybody else!!
I'm not disorganized. My room has a high entropy.
Bhelliom wrote:Don't forget that the cat probably knows EXACTLY what it is doing is is most likely just screwing with you. You know, for CAT SCIENCE!

Xanthir
My HERO!!!
Posts: 5413
Joined: Tue Feb 20, 2007 12:49 am UTC
Contact:

### Re: Sum of the digits in a number (python)

kernelpanic wrote:
Guff wrote:Alternatively, for the sake of boredom you can do it without conversion to a string through the use of modulo and integer division:

Code: Select all

`def sum_digits(n):   import math   total = 0   for i in range(int(math.log10(n)) + 1):      total += n % 10      n //= 10   return total`

Actually, that's the best I've seen (I strongly dislike strings) Thank you to you and everybody else!!

My Lisp experience suggests that using modulo/floor is much faster than an intermediary string. I gained a significant speedup when I changed my number->digits function to use direct arithmetic rather than casting to string and then to list.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

### Re: Sum of the digits in a number (python)

sparkyb wrote:
Berengal wrote:Anyway, reduce won't help much here, since the function argument needs to return something of the same type as the input values (in this case a string).
...
or define a proper fold function:
...
Note that reduce is a specialized version of this

Um, I have to correct you here. reduce is a proper fold function. Except that it's argument are in a different order (func, seq, init) with the init argument being optional. Only when you leave out the init argument does it try to use the first element of the sequence instead. So you could certainly do:

Code: Select all

`reduce(lambda sum,digit: sum+int(digit),str(number),0)`

Huh. Long time, no python...

Anyway, just to become completely esoteric:

Code: Select all

`def unfold(func, init):  l = []  (init, n) = func(init)  if init:    while init:      l.append(n)      (init, n) = func(init)    l.append(n)  return lsum(unfold(lambda n: divmod(n, 10), 12345)) == 15`

Granted, this unfold implementation is pretty horrible...
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: Sum of the digits in a number (python)

As Xanthir noted, the pure arithmetic approach may be faster than the string-based approach. Although, that's something you'd really have to profile to know for sure. And what's fast in one language doesn't always apply to other languges. This is especially true in Python. With its mix of optimized native code, sometimes it's hard to guess what is and isn't fast.

But the string-based approach is probably more Pythonic.

kernelpanic wrote:Actually, that's the best I've seen (I strongly dislike strings) Thank you to you and everybody else!!

I have to ask, why in the world do you dislike strings?

You might as well dislike integers, or bools, or any other of the traditionally fundamental datatypes. In Python no less, which definitely provides one of the better environments for string processing/manipulation.

What's wrong with strings?
Last edited by 0xBADFEED on Tue Mar 17, 2009 3:13 am UTC, edited 1 time in total.

Guff
Posts: 165
Joined: Thu Jan 03, 2008 11:56 pm UTC

### Re: Sum of the digits in a number (python)

Well, my guess (and it was entirely a guess) was based on the assumption that the behind-the-scenes conversion to string works in a similar manner to the one I worked out, with the only difference being the ASCII value offset. And I figured it's probably a bit more optimized. But then again, I've got no idea if it's implemented in C or Python.

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

### Re: Sum of the digits in a number (python)

Guff wrote:Alternatively, for the sake of boredom you can do it without conversion to a string through the use of modulo and integer division:

Code: Select all

`def sum_digits(n):   import math   total = 0   for i in range(int(math.log10(n)) + 1):      total += n % 10      n //= 10   return total`

Even still, for the sake of obfuscation it can also be written as:

Code: Select all

`sum_digits = lambda n: sum(n//(10**i) % 10 for i in range(int(math.log10(n)) + 1))`

Granted, I'm pretty sure for very large numbers it will be less efficient than a conversion to a string, but I guarantee you will pick up chicks with this method.

Not bad, but why not just do:

Code: Select all

`total = 0;while(n) {    total += n % 10;    n /= 10;}`

Guff
Posts: 165
Joined: Thu Jan 03, 2008 11:56 pm UTC

### Re: Sum of the digits in a number (python)

Rysto wrote:Not bad, but why not just do:

Code: Select all

`total = 0;while(n) {    total += n % 10;    n /= 10;}`

Just because both options were reasonable, and so I chose the for loop version because I figured it indicates that we know exactly how many iterations it'll take to get the result. No real reason for me to favor one all that more over the other, unless there's a situation where calculating the log would be too costly, but that seems highly unlikely to me.

kernelpanic
Posts: 891
Joined: Tue Oct 28, 2008 1:26 am UTC
Location: 1.6180339x10^18 attoparsecs from Earth

### Re: Sum of the digits in a number (python)

kernelpanic wrote:Actually, that's the best I've seen (I strongly dislike strings) Thank you to you and everybody else!!

I have to ask, why in the world do you dislike strings?

You might as well dislike integers, or bools, or any other of the traditionally fundamental datatypes. In Python no less, which definitely provides one of the better environments for string processing/manipulation.

What's wrong with strings?

They simply... suck. And, I hope a dog bites you for even suggesting that you can dislike integers.
I'm not disorganized. My room has a high entropy.
Bhelliom wrote:Don't forget that the cat probably knows EXACTLY what it is doing is is most likely just screwing with you. You know, for CAT SCIENCE!

Guff
Posts: 165
Joined: Thu Jan 03, 2008 11:56 pm UTC

### Re: Sum of the digits in a number (python)

You two should fight.

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: Sum of the digits in a number (python)

kernelpanic wrote:They simply... suck. And, I hope a dog bites you for even suggesting that you can dislike integers.

I'm serious. I would like to know what you dislike about strings. Or, how you even can dislike strings.

Is there some other abstraction over a sequence of characters that you prefer to use?

Do you dislike strings of all character sets?

Does it help if you to think of strings as an array/vector of bytes or shorts?

Does it generalize to a hatred of all sequence types?

Is it a particular implementation of strings that you dislike? (ntbs's do suck)

Why Two Kay
Posts: 266
Joined: Sun Mar 23, 2008 6:25 pm UTC
Location: Plano, TX
Contact:

### Re: Sum of the digits in a number (python)

kernelpanic wrote:They simply... suck. And, I hope a dog bites you for even suggesting that you can dislike integers.

I'm serious. I would like to know what you dislike about strings. Or, how you even can dislike strings.

Is there some other abstraction over a sequence of characters that you prefer to use?

Do you dislike strings of all character sets?

Does it help if you to think of strings as an array/vector of bytes or shorts?

Does it generalize to a hatred of all sequence types?

Is it a particular implementation of strings that you dislike? (ntbs's do suck)

Strings are slower than integers. This is why "BigNum" libraries are so vastly slower than primitive type ints or floats. It's not really numbers, it's a representation of a number in some other form. In the case of Strings, specific chars of '1', '2', '3', etc are not numbers, and to parse them is expensive. Modulus operations on an int or long will add together the numbers faster.
tl;dr - I said nothing important.

Outchanter
Posts: 669
Joined: Mon Dec 17, 2007 8:40 am UTC

### Re: Sum of the digits in a number (python)

Rysto wrote:Not bad, but why not just do:

Code: Select all

`total = 0;while(n) {    total += n % 10;    n /= 10;}`

You'll want //, / is floating point division in Python 3.0.

hotaru
Posts: 1045
Joined: Fri Apr 13, 2007 6:54 pm UTC

### Re: Sum of the digits in a number (python)

Why Two Kay wrote:Strings are slower than integers. This is why "BigNum" libraries are so vastly slower than primitive type ints or floats. It's not really numbers, it's a representation of a number in some other form. In the case of Strings, specific chars of '1', '2', '3', etc are not numbers, and to parse them is expensive. Modulus operations on an int or long will add together the numbers faster.

you obviously don't understand bignum libraries at all, and you've probably never used one.

Code: Select all

`factorial = product . enumFromTo 1isPrime n = factorial (n - 1) `mod` n == n - 1`

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: Sum of the digits in a number (python)

Why Two Kay wrote:Strings are slower than integers.
...snip...

As Hotaru said, character strings have nothing to do with BigNum libraries. No sensible BigNum library represents numbers with character strings. If you think about why this is true you'll realize how incredibly ridiculous that notion is.

The OP said nothing about not liking strings for arithmetic. The statement was that he dislikes strings period. Which strikes me as exceedingly odd.

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

### Re: Sum of the digits in a number (python)

Outchanter wrote:You'll want //, / is floating point division in Python 3.0.

I probably also wouldn't want braces or semicolons if I was writing Python...

You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

### Re: Sum of the digits in a number (python)

I'm not sure how well python deals with recursion, but this is how I'd do it in other languages.

Code: Select all

`def dsum(n):   if n == 0:      return 0   return n % 10 + dsum(n//10)`
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

Emu*
Posts: 689
Joined: Mon Apr 28, 2008 9:47 am UTC
Location: Cardiff, UK
Contact:

### Re: Sum of the digits in a number (python)

You, sir, name? wrote:I'm not sure how well python deals with recursion, but this is how I'd do it in other languages.

Code: Select all

`def dsum(n):   if n == 0:      return 0   return n % 10 + dsum(n//10)`

For something that simple, looping is probably more efficient...
Cosmologicon wrote:Emu* implemented a naive east-first strategy and ran it for an hour, producing results that rivaled many sophisticated strategies, visiting 614 cells. For this, Emu* is awarded Best Deterministic Algorithm!

You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

### Re: Sum of the digits in a number (python)

It entirely depends on how well python deals with tail recursion. If it's smart about it, it should be just as fast. If it isn't, it should be much slower.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

### Re: Sum of the digits in a number (python)

That's not tail-recursion. Tail-recursion always look like

Code: Select all

`def foo(...):  ...  return foo(...)`

Besides, when has python ever been clever about optimization?
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

### Re: Sum of the digits in a number (python)

Berengal wrote:That's not tail-recursion. Tail-recursion always look like

Code: Select all

`def foo(...):  ...  return foo(...)`

That's true, but it can be made into such a problem.

Code: Select all

`def dsum(n, result=0):   if n == 0:     return result   return dsum(n//10, result + n % 10)`

But this doesn't matter. Python does not optimize tail recursion, as it turns out. I tired to run dsum on 2e2000, and it crashed and burned after it hit the maximum recursion depth.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

Vempele
Posts: 69
Joined: Wed Nov 14, 2007 8:05 am UTC

### Re: Sum of the digits in a number (python)

You, sir, name? wrote:That's true, but it can be made into such a problem.

And sufficiently clever (existing!) compilers will do that for you, at least in simple cases.
const int ALMOST_FIFTY = 80;

Why Two Kay
Posts: 266
Joined: Sun Mar 23, 2008 6:25 pm UTC
Location: Plano, TX
Contact:

### Re: Sum of the digits in a number (python)

hotaru wrote:
Why Two Kay wrote:Strings are slower than integers. This is why "BigNum" libraries are so vastly slower than primitive type ints or floats. It's not really numbers, it's a representation of a number in some other form. In the case of Strings, specific chars of '1', '2', '3', etc are not numbers, and to parse them is expensive. Modulus operations on an int or long will add together the numbers faster.

you obviously don't understand bignum libraries at all, and you've probably never used one.

Why Two Kay wrote:Strings are slower than integers.
...snip...

As Hotaru said, character strings have nothing to do with BigNum libraries. No sensible BigNum library represents numbers with character strings. If you think about why this is true you'll realize how incredibly ridiculous that notion is.

The OP said nothing about not liking strings for arithmetic. The statement was that he dislikes strings period. Which strikes me as exceedingly odd.

I never said that BigNum libraries use Strings/characters to represent the data (which is why I said 'In the case of Strings...'), but they are slower since they are not primitive data types. If you were to do large repeated multiplication or even addition of numbers using a BigInteger type, it would finish much much much slower than using a regular long. This was an issue I ran into when doing Project Euler problems, since BigInteger made it easier to write, but runtime was far too great to be practical.

And I took the entire thread to have to do with Strings for arithmetic, since the thread is about adding the individual digits of a number together.
tl;dr - I said nothing important.

Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

### Re: Sum of the digits in a number (python)

Why Two Kay wrote:This was an issue I ran into when doing Project Euler problems, since BigInteger made it easier to write, but runtime was far too great to be practical.

Really? It's not something I've run into, and I've been using numbers >> 10^10000. The 100'000th fib is > 10^20000, and one problem looks for a fib > 10^68000, which took me only a few seconds to find the size of right now.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

Outchanter
Posts: 669
Joined: Mon Dec 17, 2007 8:40 am UTC

### Re: Sum of the digits in a number (python)

Rysto wrote:
Outchanter wrote:You'll want //, / is floating point division in Python 3.0.

I probably also wouldn't want braces or semicolons if I was writing Python...

D'oh!

You, sir, name? wrote:It entirely depends on how well python deals with tail recursion. If it's smart about it, it should be just as fast. If it isn't, it should be much slower.

I think Stackless Python has efficient tail recursion.

kernelpanic
Posts: 891
Joined: Tue Oct 28, 2008 1:26 am UTC
Location: 1.6180339x10^18 attoparsecs from Earth

### Re: Sum of the digits in a number (python)

kernelpanic wrote:They simply... suck. And, I hope a dog bites you for even suggesting that you can dislike integers.

I'm serious. I would like to know what you dislike about strings. Or, how you even can dislike strings.

Is there some other abstraction over a sequence of characters that you prefer to use?

Do you dislike strings of all character sets?

Does it help if you to think of strings as an array/vector of bytes or shorts?

Does it generalize to a hatred of all sequence types?

Is it a particular implementation of strings that you dislike? (ntbs's do suck)

1.- Yes, lists
2.- I don't really mind text
3.- Actually, it does. Thank you!
4.- No...
5.- Yes, to represent ints as strings
I'm not disorganized. My room has a high entropy.
Bhelliom wrote:Don't forget that the cat probably knows EXACTLY what it is doing is is most likely just screwing with you. You know, for CAT SCIENCE!

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: Sum of the digits in a number (python)

Ok, so I was bored and actually did some profiling of the two methods (string-based vs. arithmetic) in Python.

I used Guff's solution versus the string-based solution that I had posted. Guff's solution was slightly modified to remove the 'log' computation and the 'math' import statement. This sped up the arithmetic version so I think it's fine.

The results are slightly surprising.

For small numbers the arithmetic version has the definite advantage.
For numbers in the 64-bit range the methods are pretty comparable.
For large numbers the string version is substantially faster.

Now I'm sure there are better arithmetic versions but this one at least looks quite reasonable.

Testing program
Spoiler:
sandbox.py

Code: Select all

`import timeitdef do_string_conversion(num):    return sum(map(int,str(num)))        def do_arithm_conversion(num):   total = 0   while num:      total += num % 10      num //= 10   return total      def do_test(num):    numtimes = 100000    str_stmt = 'sandbox.do_string_conversion(%i)' % num    arith_stmt = 'sandbox.do_arithm_conversion(%i)' % num    str_time = timeit.Timer(str_stmt,'import sandbox').timeit(numtimes)    arith_time = timeit.Timer(arith_stmt,'import sandbox').timeit(numtimes)    return str_time,arith_timedef do_tests():   nums = [    1,    12345,    2**31,    2**63,    2**1000   ]   for n in nums:       print do_test(n)`

Times for one of the sample sets
Spoiler:

Code: Select all

`Number  : (Sring Version Time, Arithmetic Version Time) time in seconds for 100,000 iterations--------------------------------------------------------------------- 1                :  (0.24527976942749774, 0.045356809075883575) 12345            :  (0.39836235451377888, 0.13644513675626513) 2**31            :  (0.57448314714872595, 0.46222545287469075) 2**63            :  (0.91057677666208292, 0.925635117542015) 2**1000          :  (14.361347524018015, 39.490897224440687)`

kernelpanic
Posts: 891
Joined: Tue Oct 28, 2008 1:26 am UTC
Location: 1.6180339x10^18 attoparsecs from Earth

### Re: Sum of the digits in a number (python)

OK, I guess that should settle it, but we're not arguing about that. I say I don't like strings in general, and you find that offensive/idiotic/unsettling/any combination of the three. But you seem so convinced, I'll practice more strings, and in return I expect you to know what you are arguing about.
I'm not disorganized. My room has a high entropy.
Bhelliom wrote:Don't forget that the cat probably knows EXACTLY what it is doing is is most likely just screwing with you. You know, for CAT SCIENCE!

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: Sum of the digits in a number (python)

kernelpanic wrote:OK, I guess that should settle it, but we're not arguing about that. I say I don't like strings in general, and you find that offensive/idiotic/unsettling/any combination of the three. But you seem so convinced, I'll practice more strings, and in return I expect you to know what you are arguing about.

My last post was a complete aside and had nothing to do with our conversation about strings. There was some uncertainty earlier in the thread about whether the arithmetic or string-based version would be faster. That piqued my interest and I thought I'd find out.

I just don't know what to say about your dislike of strings. They're just so darn useful. They allow for the same operations as any other sequence-based container plus a whole host of other useful utilities that are specific to character sequences. A 'list' of characters (really strings) in Python offers no advantage over a string and has lots of disadvantages. I think you'll find it hard to go very far in programming with such disregard for the mighty string.

Xanthir
My HERO!!!
Posts: 5413
Joined: Tue Feb 20, 2007 12:49 am UTC
Contact:

### Re: Sum of the digits in a number (python)

kernelpanic wrote:OK, I guess that should settle it, but we're not arguing about that. I say I don't like strings in general, and you find that offensive/idiotic/unsettling/any combination of the three. But you seem so convinced, I'll practice more strings, and in return I expect you to know what you are arguing about.

Dude, the reason it sounds idiotic is because you're saying you don't like a *basic data structure*. They're arrays. That's, um, it. We just interpret them in a special way, same as we might interpret a struct of two ints as a complex number. What's there to dislike?
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

Outchanter
Posts: 669
Joined: Mon Dec 17, 2007 8:40 am UTC

### Re: Sum of the digits in a number (python)

To be fair, you can dislike certain implementations of strings. For example, immutable strings which end up taking O(n^2) time to build in a naive loop because every concatenation requires creating an entirely new string.

Xanthir
My HERO!!!
Posts: 5413
Joined: Tue Feb 20, 2007 12:49 am UTC
Contact:

### Re: Sum of the digits in a number (python)

Yes, of course, but then you're talking about a particular implementation. That's perfectly reasonable to dislike in particular circumstances.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

Pomegranete
Posts: 8
Joined: Tue Aug 18, 2009 12:29 am UTC

### Re: Sum of the digits in a number (python)

sorry to bump and all, but i couldn't let this thread go by without sharing the much easier;

Code: Select all

`sum(int(each_numeral) for each_numeral in str(num))`

thoughtfully
Posts: 2253
Joined: Thu Nov 01, 2007 12:25 am UTC
Location: Minneapolis, MN
Contact:

### Re: Sum of the digits in a number (python)

kernelpanic wrote:They simply... suck. And, I hope a dog bites you for even suggesting that you can dislike integers.

I tend to agree. This is an arithmetic problem, and using strings obscures the underlying math. Why convert to strings then back, anyway? Also, (not in this case, since the character codes aren't relevant) using strings implies adopting an arbitrary convention when you really don't need to. It's inelegant. And strings suck (in Python) because you can't recurse with them, at least not without doing silly things you'd never do for any other sequence type. Ugh, it makes my brain hurt!

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.
-- Antoine de Saint-Exupery

Cleverbeans
Posts: 1378
Joined: Wed Mar 26, 2008 1:16 pm UTC

### Re: Sum of the digits in a number (python)

Or as an alternative to Pomegranete's scheme is to use map and list rather than a generator.

Code: Select all

`sum(map(int,list(str(n))))`

I call this Pilate style, for obvious reasons. Well, obvious to me and Biggus Dickus anyway.
"Labor is prior to, and independent of, capital. Capital is only the fruit of labor, and could never have existed if labor had not first existed. Labor is the superior of capital, and deserves much the higher consideration." - Abraham Lincoln

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: Sum of the digits in a number (python)

Cleverbeans wrote:Or as an alternative to Pomegranete's scheme is to use map and list rather than a generator.

Code: Select all

`sum(map(int,list(str(n))))`

I call this Pilate style, for obvious reasons. Well, obvious to me and Biggus Dickus anyway.

There's no reason to convert the string to to a list. A Python string is already a sequence and is completely compatible with 'map'. This is the solution I offered in the second post of the thread.