larn
larn

Reputation: 398

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.

So, for example: 0, 5, and 14 would be the first three digits that print out in this instance.

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.

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.

I know that digit % 5 == 0 is totally wrong, but I'm all out of ideas! Any help and/or words of wisdom would be greatly appreciated.

Upvotes: 4

Views: 403

Answers (5)

Subham
Subham

Reputation: 411

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]

Upvotes: 0

Eriall
Eriall

Reputation: 316

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:

print([digit for digit in range(0,100) if (sum([int(i) for i in str(digit)]) % 5==0)])

Upvotes: 5

DYZ
DYZ

Reputation: 57105

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.

Upvotes: 0

thebjorn
thebjorn

Reputation: 27351

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]

Upvotes: 3

user10400458
user10400458

Reputation:

If you really want a one-liner (I think your current solution is more readable):

print(*(i for i in range(101) if sum(int(j) for j in str(i))%5 == 0))

Upvotes: 1

Related Questions