3 ms·
> write a program which calculates the sum of all numbers between 1 and 1,000 whose digits sum up to 7 My Python answer: sum(x for x in xrange(2, 1000) if s
by BrandonM 16y ago
> write a program which calculates the sum of all numbers between 1 and 1,000 whose digits sum up to 7
My Python answer:
sum(x for x in xrange(2, 1000) if sum(int(y) for y in str(x)) == 7)
# 9324
Anyone have improvements on that?
(I used the range (1, 1000) as opposed to [1, 1000], but it doesn't make a difference since the edge values don't have digits that sum to 7.)
- kenjackson 16y agoThere are a lot of micro improvements you can do to this. For example, after you find sum() == 7, you can increment x by 9 (since the largest digit in the ones column can be 7, and this takes a deficit of two digits to get back to the rollover -- and then 7 more to get a sum of 7 again). And frankly I'm not sure if its faster to convert to string and back to int, or if it would be better to just use modulo arithmitic to get the values associated with the ones/tens/hundreds. In any case, what you have is certainly readable though.
- BrandonM 16y agoI mainly meant "improve" in terms of conciseness and readability. I didn't see any need for optimization because the snippet runs instantly: $ time python -c "print sum(x for x in xrange(2, 1000) if sum(int(y) for y in str(x)) == 7)" 9324 real 0m0.138s user 0m0.012s sys 0m0.012s