[英]Python counting zeros
I have created a code which basically generates a random 20 digit number. 我创建了一个代码,该代码基本上会生成一个随机的20位数字。 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. 现在给出此代码,我只是想知道如何计算输出中的零个数,因此本质上我试图创建一个名为
count_zero():
的新函数,但是我不知道该怎么写我的参数,什么不是。
Turn the number into a string and count the number of '0'
characters: 将数字转换为字符串并计算
'0'
字符的数量:
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: 您可以直接传递
digit()
的结果或先存储结果,然后将其传递给:
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.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.