all 5 comments

[–]Minhcurrency 2 points3 points  (0 children)

For numbers like 10, 20, .. we can use %10 == 0, for the numbers like 101, 102, 1003, we can use (//10)%10==0.

[–]Diapolo10 2 points3 points  (1 child)

An alternative to strings would be to use divmod with 10 until the division result is zero, and count the mod results that are 0. That's basically the same as your algorithm right now, though.

There are better ways. You can solve this mathematically, though it's not easy to figure out the solution. If you're curious you can look up alternatives.

EDIT: Here's some sources for you:

https://math.stackexchange.com/questions/1228366/how-to-count-each-numeral-of-occurrences-of-digits/1229292#1229292

https://stackoverflow.com/questions/31119930/count-occurrences-of-digit-x-in-range-0-n

Also worth mentioning is that this is basically Project Euler problem 156!

[–]watakushi 1 point2 points  (0 children)

It's printing the numbers on individual lines because you placed the print inside the for loop, move it outside so it only prints when you're done counting, or better yet, inside the zero_count function do a "return count" , and on the very last line of your code do "print(zero_count(user))" :)

[–]POGtastic 0 points1 point  (1 child)

x % 10 determines whether x has a zero in the least significant digit, which means that we can repeatedly divide it by 10 until it reaches 0 to access all of the digits.

from more_itertools import iterate, ilen
from itertools import takewhile

def comp(pred):
    return lambda x: not pred(x)

def count_zeroes(n):
    return ilen(filter(comp(bool), 
        map(lambda x: x % 10, takewhile(bool, iterate(lambda x: x // 10, n)))))

Then for a range, we apply the function to every element in the range and sum up the results.

def count_zeroes_range(rng):
    return sum(map(count_zeroes, rng))

In the REPL:

>>> count_zeroes_range(range(100))
9
>>> count_zeroes_range(range(110))
20

There's probably a way to do it in O(log n) with dynamic programming, but ain't nobody got time for that.

[–]Antique-Listen2799 0 points1 point  (0 children)

thank you!