Fastest way to create strictly increasing lists in Python

后端 未结 5 2112
南方客
南方客 2021-02-07 09:03

I would like to find out what is the most efficient way to achieve the following in Python:

Suppose we have two lists a and b which are of equa

5条回答
  •  -上瘾入骨i
    2021-02-07 09:24

    Running a version of @juanpa.arrivillaga's function with numba

    import numba
    
    def psi(A):
        a_cummax = np.maximum.accumulate(A)
        a_new, idx = np.unique(a_cummax, return_index=True)
        return idx
    
    def foo(arr):
        aux=np.maximum.accumulate(arr)
        flag = np.concatenate(([True], aux[1:] != aux[:-1]))
        return np.nonzero(flag)[0]
    
    @numba.jit
    def f(A):
        m = A[0]
        a_new, idx = [m], [0]
        for i, a in enumerate(A[1:], 1):
            if a > m:
                m = a
                a_new.append(a)
                idx.append(i)
        return idx
    

    timing

    %timeit f(a)
    The slowest run took 5.37 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000000 loops, best of 3: 1.83 µs per loop
    
    %timeit foo(a)
    The slowest run took 9.41 times longer than the fastest. This could mean that an intermediate result is being cached.
    100000 loops, best of 3: 6.35 µs per loop
    
    %timeit psi(a)
    The slowest run took 9.66 times longer than the fastest. This could mean that an intermediate result is being cached.
    100000 loops, best of 3: 9.95 µs per loop
    

提交回复
热议问题