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.
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.
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
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
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.
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