问题
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)
range_end = (10**n)-1
return randint(range_start, range_end+1)
print(digit(n))
The output of this code for example is:
49690101904335902069
Now given this code I'm just wondering how I can go about to counting the number of zeros in the output, so essentially I'm trying to create a new function called count_zero():
, but I have no idea what to put it for my parameter and what not.
回答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.')
来源:https://stackoverflow.com/questions/29155162/python-counting-zeros