2017-04-06 54 views
-2

下面的代码片段用于返回不包含重复数字的数字的数字。如何优化下面的python代码片段?

例如,如果输入是7,程序应该返回数字计数7计数(1,2,3,4,5,6,7)然后输出应该是7

如果输入为23的程序应该返回数字的计数的(1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,23)这里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 
+5

可能是https://codereview.stackexchange.com/的候选人 – languitar

+2

这种形式的问题可能不会在Code Review中得到很好的回应,因为它缺少关于代码的所有上下文,并且可能会被关闭为不清楚。如果要在那里发布,我强烈建议添加更多的上下文。 – Phrancis

+1

“优化此代码”是什么意思?你想优化源代码的长度吗?性能?使用的功能数量?源代码的可读性?... – kravemir

回答

-1

与慢 'Python化' 的解决方案如何能够始终感到惊讶。下面是使用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 
+0

任何评论为什么这是值得downvote? – user3684792