对数字的数字求和 - python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14939953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum the digits of a number - python
提问by SpFW
If I want to find the sum of the digits of a number, i.e. :
如果我想找到一个数字的数字总和,即:
- Input:
932 - Output:
14, which is(9 + 3 + 2)
- 输入:
932 - 输出:
14,即(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?
哪个最适合用于速度,还有其他更快的方法吗?
采纳答案by Pavel Anossov
Both lines you posted are fine, but 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:
或与divmod:
def sum_digits2(n):
s = 0
while n:
n, remainder = divmod(n, 10)
s += remainder
return s
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
回答by Aftab Lateef
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
回答by d8aninja
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:
如果您想继续对数字求和,直到得到一位数(我最喜欢的可被 9 整除的数字特征之一),您可以执行以下操作:
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
回答by Tsvetelin Tsvetkov
Doing some Codecademy challenges I resolved this like:
做一些 Codecademy 挑战,我解决了这个问题:
def digit_sum(n):
arr = []
nstr = str(n)
for x in nstr:
arr.append(int(x))
return sum(arr)
回答by Abdullah Asif
n = str(input("Enter the number\n"))
list1 = []
for each_number in n:
list1.append(int(each_number))
print(sum(list1))
回答by Arghyadeep Giri
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.
“结果”初始化为 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]
在 for 循环中,number(n) 被转换成一个字符串,用循环 index(i) 分割并得到每个数字。---> str(n)[ i:i+1]
This sliced digit is converted back to an integer ----> int(str(n)[i:i+1])
这个切片后的数字被转换回整数----> int(str(n)[i:i+1])
And hence added to result.
因此添加到结果中。
回答by Jayant Pandey
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
print(sum) // 确保在此行上方添加空格
回答by Julisam
You can try this
你可以试试这个
def sumDigits(number):
sum = 0
while(number>0):
lastdigit = number%10
sum += lastdigit
number = number//10
return sum
回答by itachi
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()
回答by simran sinha
you can also try this with built_in_function called divmod() ;
您也可以使用名为 divmod() 的 built_in_function 尝试此操作;
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
你可以取任意数量的数字

