如何优化下面的python代码段?

2024-04-25 00:54:14 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码段用于返回不包含重复数字的数字。你知道吗

例如,如果输入是7,程序应该返回数的计数(1,2,3,4,5,6,7)的7个计数,那么输出应该是7。你知道吗

如果输入是23,程序应该返回数的计数23数的(1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,23),这里的计数排除了11,22这样的数字,输出应该是21。你知道吗

要优化此代码,我应该怎么做?你知道吗

def nonrep1(n):
    return sum(all(c != d for c, d in zip(str(i), str(i)[1:])) for i in xrange(1, n+1))

我必须优化这个代码,我该怎么做?你知道吗

测试用例1:

simple input:

7

simple output:

7

测试用例2:

simple input:

3456

simple output:

2562

Tags: 代码in程序forinputoutputreturndef
1条回答
网友
1楼 · 发布于 2024-04-25 00:54:14

总是惊讶于“pythonic”解决方案的速度有多慢。下面是使用cython的80加速系数:

from libc.math cimport log10
from cython.operator cimport preincrement as preinc
import cython

@cython.cdivision(True)
cdef int add_number(int i):
    cdef int cur_last = i % 10, next_last = 0
    cdef int cur_val = i / 10

    cdef int jj = 0
    for jj in xrange(int(log10(cur_val) + 1)):
        next_last = cur_val % 10
        if next_last == cur_last:
            return 0
        cur_val /= 10
        cur_last = next_last

    return 1

cpdef int cython_nonrep1(int n):
    cdef int s = 0
    cdef int i = 0
    if n < 10:
        return n

    for i in xrange(10, n+1):
        s += add_number(i)
    return s

要使用它,请将其保存在.pyx文件中并使用pyximport(或使用distutils等构建它)

一些基准:

%timeit nonrep1(3456)
100 loops, best of 3: 4.92 ms per loop


% timeit cython_nonrep1(3456)
10000 loops, best of 3: 63.4 µs per loop

相关问题 更多 >