【问题标题】:How to optimize the following python snippet?如何优化以下python片段?
【发布时间】:2017-04-06 08:29:30
【问题描述】:

下面的代码 sn-p 用于返回不包含重复数字的数字的数字。

例如,如果输入为 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:

简单输入:

7

简单的输出:

7

测试用例 2:

简单输入:

3456

简单的输出:

2562

【问题讨论】:

  • 可能是codereview.stackexchange.com的候选人
  • 这种形式的问题在 Code Review 中可能不会被很好地接受,因为它缺乏关于代码用途的所有上下文,并且可能会因为不清楚而被关闭。如果要在那里发布,我强烈建议添加更多上下文。
  • “优化此代码”是什么意思?你想优化源代码的长度吗?表现?使用的功能数量?源代码的可读性?...
  • 性能和使用的函数数量@kravemir
  • 我正在看这个,所以请不要关闭问题

标签: python


【解决方案1】:

总是对“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

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2013-05-15
    • 1970-01-01
    • 2013-02-15
    • 2016-09-13
    • 2012-08-21
    相关资源
    最近更新 更多