3

Let say I have

num = 123456

How do I get the digit sum which is 21? How to use the sum() function? I tried sum(num) but it says 'int' object is not iterable.

Alexa Elis
  • 7,149
  • 6
  • 17
  • 11
  • Do you mean the digit sum? http://en.wikipedia.org/wiki/Digit_sum If yes, please add that to the title, becuase haters will downvote you otherwise... – MentholBonbon Apr 28 '13 at 18:22
  • sum works on iterable objects like lists. strings also happen to be iterable (sort of like a list of characters). a number is just one thing. if you want to sum a list of different numbers, you would want `num` to be something like `[1,2,3,4,5,6]` which is a list of the numbers you want to sum. – underrun Apr 28 '13 at 18:25
  • @MentohlBonbon yup, that's what I meant. Thanks! – Alexa Elis Apr 28 '13 at 18:25
  • @AlexaElis I hate it when people downvote questions just because they don't understand them – MentholBonbon Apr 28 '13 at 18:41
  • @MentohlBonbon haha thanks again for correcting my question title :) – Alexa Elis Apr 28 '13 at 18:55
  • 2
    @MentohlBonbon To be fair, I think everyone understood it, but downvoted the lack of research effort. – keyser Apr 28 '13 at 19:12
  • What do you mean by "the sum of the num which is 21"? `num` is being set to 123456, not 21. – Anderson Green Apr 28 '13 at 20:39

4 Answers4

13

You have to change it to a string first :

In [24]: num = 123456

In [25]: sum(int(x) for x in str(num))
Out[25]: 21

Without converting to a string:

def solve(n):
    summ=0
    while n:
        summ+= n%10
        n/=10
    return summ
   ....: 

In [38]: solve(123456)
Out[38]: 21
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
8

One way:

In [1]: num=123456

In [2]: sum(map(int,str(num)))
Out[2]: 21

In [3]: def digitsum(x):
   ...:     return sum(map(int,str(x)))
   ...: 

In [4]: digitsum(num)
Out[4]: 21
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
3

You can do it like this:

sum(map(int,list(str(num))))  #sum contains your digits string

str(num) return a string version of your number, list(...) makes a list out of your string (char by char), map(int,string) applies an integer cast to your list. Now your list includes all the single integers of your number, so you can use your sum() function.

1

How about this:

def f(num):
  result = 0
  base = 10
  pos = 10
  while pos <= num*base:
    prev = pos/base
    result = result + int( (num % pos)/ prev)
    pos = pos*base
  return result
MentholBonbon
  • 745
  • 4
  • 10