Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 631
larn Avatar asked Jan 01 '23 08:01

larn


1 Answers

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)])
like image 145
Eriall Avatar answered Jan 05 '23 17:01

Eriall