Python计数零 [英] Python counting zeros

查看:89
本文介绍了Python计数零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个代码,该代码基本上会生成一个随机的20位数字.下面的代码:

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

现在给定了这段代码,我只是想知道如何计算输出中的零个数,因此本质上我正在尝试创建一个名为 count_zero():的新函数.,但我不知道该在参数中加上什么.

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.

推荐答案

将数字转换为字符串并计算'0'个字符的数量:

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

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

演示:

>>> 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

后一种方法比很多慢一些:

>>> 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()的结果,也可以先把结果存起来,再传入:

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.')

这篇关于Python计数零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆