给定一个数字n,计算包括n在内的数字0、2和4的出现次数.

示例1:

n = 10
output: 4

Example2:
n = 22
output: 11

我的代码:

n = 22

def count_digit(n):
    count = 0
    for i in range(n+1):
        if '2' in str(i):
            count += 1
        if '0' in str(i):
            count += 1
        if '4' in str(i):
            count += 1
    return count

count_digit(n)

编码输出:10

==同步,由长者更正==

约束:1 <= N <= 10^5

注:The solution should not cause 100 or 101 for large numbers.

推荐答案

另一种 brute 的力量,似乎更快:

def count_digit(n):
    s = str(list(range(n+1)))
    return sum(map(s.count, '024'))

基准:n = 10**5:

result   time   solution

115474  244 ms  original
138895   51 ms  Kelly
138895  225 ms  islam_abdelmoumen
138895  356 ms  CodingDaveS

代码(Try it online!):

from timeit import default_timer as time

def original(n):
    count = 0
    for i in range(n+1):
        if '2' in str(i):
            count += 1
        if '0' in str(i):
            count += 1
        if '4' in str(i):
            count += 1
    return count

def Kelly(n):
    s = str(list(range(n+1)))
    return sum(map(s.count, '024'))

def islam_abdelmoumen(n):
    count = 0
    for i in map(str,range(n+1)):
        count+=i.count('0')
        count+=i.count('2')
        count+=i.count('3')
    return count

def CodingDaveS(n):
    count = 0
    for i in range(n + 1):
        if '2' in str(i):
            count += str(i).count('2')
        if '0' in str(i):
            count += str(i).count('0')
        if '4' in str(i):
            count += str(i).count('4')
    return count

funcs = original, Kelly, islam_abdelmoumen, CodingDaveS

print('result   time   solution')
print()
for _ in range(3):
    for f in funcs:
        t = time()
        print(f(10**5), ' %3d ms ' % ((time()-t)*1e3), f.__name__)
    print()

Python相关问答推荐

Python中的负前瞻性regex遇到麻烦

Python plt.text中重叠,包adjust_text不起作用,如何修复?

如何在Python中使用时区夏令时获取任何给定本地时间的纪元值?

通过优化空间在Python中的饼图中添加标签

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

如何在Windows上用Python提取名称中带有逗号的文件?

如何更改分组条形图中条形图的 colored颜色 ?

如何从需要点击/切换的网页中提取表格?

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

找到相对于列表索引的当前最大值列表""

为什么'if x is None:pass'比'x is None'单独使用更快?

Python避免mypy在相互引用中从另一个类重定义类时失败

从旋转的DF查询非NaN值

在Python中从嵌套的for循环中获取插值

提高算法效率的策略?

如何删除重复的文字翻拍?

使用tqdm的进度条

Django在一个不是ForeignKey的字段上加入'

如何根据一定条件生成段id

为什么我只用exec()函数运行了一次文件,而Python却运行了两次?