我创建的代码基本上生成一个随机的20位数字。代码如下:
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))
此代码的输出例如是:
49690101904335902069
现在给出这段代码,我只是想知道如何计算输出中的零数,所以基本上我正在尝试创建一个名为count_zero():
的新函数,但我不知道什么把它放在我的参数和什么没有。
答案 0 :(得分:9)
将数字转换为字符串并计算'0'
个字符的数量:
def count_zeros(number):
return str(number).count('0')
演示:
>>> def count_zeros(number):
... return str(number).count('0')
...
>>> count_zeros(49690101904335902069)
5
或者不将其变成字符串:
def count_zeros(number):
count = 0
while number > 9:
count += int(number % 10 == 0)
number //= 10
return count
后一种方法是 lot 然而慢:
>>> 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
要将其与您的代码结合使用,只需添加该功能,然后分别调用;您可以直接传递digit()
的结果或先存储结果,然后将其传递给:
print(count_zeros(digit(n)))
或单独(允许您显示结果随机数):
result = digit(n)
zeros = count_zeros(result)
print('result', result, 'contains', zeros, 'zeros.')