问题
If I want to find the sum of the digits of a number, i.e. :
- Input:
932
- Output:
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?
回答1:
You can do it purely in integers, and it will be the most efficient:
def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
or with divmod
:
def sum_digits2(n):
s = 0
while n:
n, remainder = divmod(n, 10)
s += remainder
return s
But both lines you posted are fine.
Even faster is the version without augmented assignments:
def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
> %timeit sum_digits(n)
1000000 loops, best of 3: 574 ns per loop
> %timeit sum_digits2(n)
1000000 loops, best of 3: 716 ns per loop
> %timeit sum_digits3(n)
1000000 loops, best of 3: 479 ns per loop
> %timeit sum(map(int, str(n)))
1000000 loops, best of 3: 1.42 us per loop
> %timeit sum([int(digit) for digit in str(n)])
100000 loops, best of 3: 1.52 us per loop
> %timeit sum(int(digit) for digit in str(n))
100000 loops, best of 3: 2.04 us per loop
回答2:
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
回答3:
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
回答4:
Doing some Codecademy challenges I resolved this like:
def digit_sum(n):
arr = []
nstr = str(n)
for x in nstr:
arr.append(int(x))
return sum(arr)
回答5:
You can also use this:
def sum_digits(num):
num = str(num)
digitSum = 0
for i in num:
digitSum += int(i)
return digitSum
print sum_digits(875)
回答6:
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.
回答7:
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()
回答8:
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
回答9:
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)]))
回答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
回答11:
Try this
print(sum(list(map(int,input("Enter your number ")))))
回答12:
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
回答13:
You can try this
def sumDigits(number):
sum = 0
while(number>0):
lastdigit = number%10
sum += lastdigit
number = number//10
return sum
回答14:
n = str(input("Enter the number\n"))
list1 = []
for each_number in n:
list1.append(int(each_number))
print(sum(list1))
来源:https://stackoverflow.com/questions/14939953/sum-the-digits-of-a-number-python