If I want to find the sum of the digits of a number, i.e.:
932
14
, which is (9 + 3 + 2)
What is the fastest way of doing this?
I instinctively did:
sum(int(digit) for digit in str(number))
and I found this online:
sum(map(int, str(number)))
Which is best to use for speed, and are there any other methods which are even faster?
num = 123
dig = 0
sum = 0
while(num > 0):
dig = int(num%10)
sum = sum+dig
num = num/10
print(sum) // make sure to add space above this line
You can try this
def sumDigits(number):
sum = 0
while(number>0):
lastdigit = number%10
sum += lastdigit
number = number//10
return sum
Here is a solution without any loop or recursion but works for non-negative integers only (Python3):
def sum_digits(n):
if n > 0:
s = (n-1) // 9
return n-9*s
return 0
you can also try this with built_in_function called divmod() ;
number = int(input('enter any integer: = '))
sum = 0
while number!=0:
take = divmod(number, 10)
dig = take[1]
sum += dig
number = take[0]
print(sum)
you can take any number of digit
I cam up with a recursive solution:
def sumDigits(num):
# print "evaluating:", num
if num < 10:
return num
# solution 1
# res = num/10
# rem = num%10
# print "res:", res, "rem:", rem
# return sumDigits(res+rem)
# solution 2
arr = [int(i) for i in str(num)]
return sumDigits(sum(arr))
# print(sumDigits(1))
# print(sumDigits(49))
print(sumDigits(439230))
# print(sumDigits(439237))
def sumOfDigits():
n=int(input("enter digit:"))
sum=0
while n!=0 :
m=n%10
n=n/10
sum=int(sum+m)
print(sum)
sumOfDigits()
Found this on one of the problem solving challenge websites. Not mine, but it works.
num = 0 # replace 0 with whatever number you want to sum up
print(sum([int(k) for k in str(num)]))
n = str(input("Enter the number\n"))
list1 = []
for each_number in n:
list1.append(int(each_number))
print(sum(list1))
Doing some Codecademy challenges I resolved this like:
def digit_sum(n):
digits = []
nstr = str(n)
for x in nstr:
digits.append(int(x))
return sum(digits)
It only works for three-digit numbers, but it works
a = int(input())
print(a // 100 + a // 10 % 10 + a % 10)
reduce(op.add,map(int,list(str(number))))
Test:
from datetime import datetime
number=49263985629356279356927356923569976549123548126856926293658923658923658923658972365297865987236523786598236592386592386589236592365293865923876592385623987659238756239875692387659238756239875692856239856238563286598237592875498259826592356923659283756982375692835692385653418923564912354687123548712354827354827354823548723548235482735482354827354823548235482354823548235482735482735482735482354823548235489235648293548235492185348235481235482354823548235482354823548235482354823548234
startTime = datetime.now()
for _ in range(0,100000) :
out=reduce(op.add,map(int,list(str(number))))
now=datetime.now()
runningTime=(now - startTime)
print ("Running time:%s" % runningTime)
print(out)
Running time:0:00:13.122560 2462
This might help
def digit_sum(n):
num_str = str(n)
sum = 0
for i in range(0, len(num_str)):
sum += int(num_str[i])
return sum
If you want to keep summing the digits until you get a single-digit number (one of my favorite characteristics of numbers divisible by 9) you can do:
def digital_root(n):
x = sum(int(digit) for digit in str(n))
if x < 10:
return x
else:
return digital_root(x)
Which actually turns out to be pretty fast itself...
%timeit digital_root(12312658419614961365)
10000 loops, best of 3: 22.6 µs per loop
Here is the best solution I found:
function digitsum(n) {
n = n.toString();
let result = 0;
for (let i = 0; i < n.length; i++) {
result += parseInt(n[i]);
}
return result;
}
console.log(digitsum(192));
Try this
print(sum(list(map(int,input("Enter your number ")))))
def digitsum(n):
result = 0
for i in range(len(str(n))):
result = result + int(str(n)[i:i+1])
return(result)
"result" is initialized with 0.
Inside the for loop, the number(n) is converted into a string to be split with loop index(i) and get each digit. ---> str(n)[i:i+1]
This sliced digit is converted back to an integer ----> int(str(n)[i:i+1])
And hence added to result.
The best way is to use math.
I knew this from school.(kinda also from codewars)
def digital_sum(num):
return (num % 9) or num and 9
Just don't know how this works in code, but I know it's maths
If a number is divisible by 9 then, it's digital_sum will be 9,
if that's not the case then num % 9
will be the digital sum.
A base 10 number can be expressed as a series of the form
a × 10^p + b × 10^p-1 .. z × 10^0
so the sum of a number's digits is the sum of the coefficients of the terms.
Based on this information, the sum of the digits can be computed like this:
import math
def add_digits(n):
# Assume n >= 0, else we should take abs(n)
if 0 <= n < 10:
return n
r = 0
ndigits = int(math.log10(n))
for p in range(ndigits, -1, -1):
d, n = divmod(n, 10 ** p)
r += d
return r
This is effectively the reverse of the continuous division by 10 in the accepted answer. Given the extra computation in this function compared to the accepted answer, it's not surprising to find that this approach performs poorly in comparison: it's about 3.5 times slower, and about twice as slow as
sum(int(x) for x in str(n))
Source: Stackoverflow.com