Skip to content Skip to sidebar Skip to footer

Python Counting Zeros

I have created a code which basically generates a random 20 digit number. Code below: import random from random import randint n=20 def digit(n): range_start = 10**(n-1)

Solution 1:

Turn the number into a string and count the number of '0' characters:

def count_zeros(number):
    return str(number).count('0')

Demo:

>>> def count_zeros(number):
...     return str(number).count('0')
... 
>>> count_zeros(49690101904335902069)
5

Or without turning it into a string:

def count_zeros(number):
    count = 0
    while number > 9:
        count += int(number % 10 == 0)
        number //= 10
    return count

The latter approach is a lot slower however:

>>> import random
>>> import timeit
>>> test_numbers = [random.randrange(10 ** 6) for _ in xrange(1000)]
>>> def count_zeros_str(number):
...     return str(number).count('0')
... 
>>> def count_zeros_division(number):
...     count = 0
...     while number > 9:
...         count += int(number % 10 == 0)
...         number //= 10
...     return count
... 
>>> timeit.timeit('[c(n) for n in test_numbers]',
...     'from __main__ import test_numbers, count_zeros_str as c', number=5000)
2.4459421634674072
>>> timeit.timeit('[c(n) for n in test_numbers]',
...     'from __main__ import test_numbers, count_zeros_division as c', number=5000)
7.91981315612793

To combine this with your code, just add the function, and call it separately; you can pass in the result of digit() directly or store the result first, then pass it in:

print(count_zeros(digit(n)))

or separately (which allows you to show the resulting random number too):

result = digit(n)
zeros = count_zeros(result)
print('result', result, 'contains', zeros, 'zeros.')

Post a Comment for "Python Counting Zeros"