[英]Digit sum of certain number in python
I'm currently working on a piece of code that generates the digit sum of numbers and prints them ONLY IF they are multiples of 5.我目前正在编写一段代码,该代码生成数字的数字总和并仅在它们是 5 的倍数时才打印它们。
So, for example: 0, 5, and 14 would be the first three digits that print out in this instance.因此,例如:0、5 和 14 将是本例中打印出来的前三位数字。
num = 0
while num < 100:
sums = sum([int(digit) for digit in str(num)])
if sums % 5 == 0: #determines if the sum is a multiple of 5
print(num)
num += 1
And this code works great!这段代码效果很好! Definitely gets the job done for the sums between 1 and 100. However, I don't have a ton of experience in python and figured I'd push myself and try and get it done in one line of code instead.
绝对可以完成 1 到 100 之间的总和。但是,我在 python 方面没有很多经验,并认为我会推动自己并尝试在一行代码中完成它。
Currently, this is what I'm working with:目前,这就是我正在使用的:
print(sum(digit for digit in range(1,100) if digit % 5 == 0))
I feel like I'm somewhere along the right track, but I can't get the rest of the way there.我觉得我在正确的轨道上的某个地方,但我无法到达那里的其余部分。 Currently, this code is spitting out 950.
目前,此代码正在吐出 950。
I know that digit % 5 == 0
is totally wrong, but I'm all out of ideas!我知道
digit % 5 == 0
是完全错误的,但我完全没有想法! Any help and/or words of wisdom would be greatly appreciated.任何帮助和/或智慧之言将不胜感激。
This seems to work for me这似乎对我有用
print([digit for digit in range(1,100) if (sum([int(i) for i in str(digit)]) % 5==0)])
or if you want to include the 0:或者如果你想包括 0:
print([digit for digit in range(0,100) if (sum([int(i) for i in str(digit)]) % 5==0)])
With less parenthesis etc.:少括号等:
>>> [n for n in range(100) if sum(int(d) for d in str(n)) % 5 == 0]
[0, 5, 14, 19, 23, 28, 32, 37, 41, 46, 50, 55, 64, 69, 73, 78, 82, 87, 91, 96]
如果你真的想要一个单线(我认为你当前的解决方案更具可读性):
print(*(i for i in range(101) if sum(int(j) for j in str(i))%5 == 0))
You may use two nested list comprehensions: one will generate a list of tuples of numbers and their sums of digits, and the other will select those that meet your condition:您可以使用两个嵌套列表推导式:一个将生成数字元组及其数字总和的列表,另一个将选择满足您条件的那些:
[num for num,s in
[(x, sum(int(digit) for digit in str(x))) # The inner one
for x in range(100)]
if s % 5 == 0]
#[0, 5, 14, 19, 23, 28, 32, 37, 41, 46, 50, 55, 64...]
Other solutions are possible, too.其他解决方案也是可能的。
Adding long code for readability,添加长代码以提高可读性,
#separating each digits within number
def sum_digits(number):
res = 0
for x in str(number): res += int(x)
return res
num_list = []
for number in range(0, 100):
if sum_digits(number) % 5 == 0:
num_list.append(number)
print(num_list)
gives给
[0, 5, 14, 19, 23, 28, 32, 37, 41, 46, 50, 55, 64, 69, 73, 78, 82, 87, 91, 96]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.