Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (16.4k points)

Look at the below code, in which I have two arrays:

t1 = np.array([0,13,22,...,99994])

t2 = np.array([4,14,25,...,99998])

I'm searching for an efficient way to create an output like this:

np.array([0,1,2,3,4,13,14,22,23,24,25,...,99994,99995,99996,99997,99998])

One way to do this is:

np.array([i for a, b in zip(t1, t2) for i in range(a, b + 1)])

But, this solution is moderate and I am sure that it can, in any case, be inconceivably improved by altogether replacing the zip and list comprehension combo for certain functions completely in Numpy, it is only that I don't have the foggiest idea how. Can you folks show me the most proficient approach to do it?

The below code helps to generate two arrays:

import numpy as np

m =10000

Z = np.arange(0,10*m,10)

t1 = np.random.randint(5, size =m ) + Z

t2 =np.random.randint(5,size = m) + 5 + Z

1 Answer

0 votes
by (26.4k points)

You can use namba, here:

from numba import njit

@njit

def n_ranges_nb(t1, t2):

    a = np.arange(np.max(t2)+1)

    n = (t2 - t1).sum()

    out = np.zeros(n)

    l, l_old = 0, 0

    for i,j in zip(t1, t2):

        l += j-i

        out[l_old:l] = a[i:j]

        l_old = l

    return out

Checking with the similar values as above:

t1 = np.array([0,13,22])

t2 = np.array([4,14,25])

n_ranges_nb(t1, t2+1)

# array([ 0.,  1.,  2.,  3.,  4., 13., 14., 22., 23., 24., 25.])

Now, Let's have look at the timings:

d = 100

perfplot.show(

    setup=lambda n: np.cumsum(np.random.randint(0, 50, n)),

    kernels=[

        lambda x: np.array([i for a, b in zip(x,x+d) for i in range(a,b+1)]),

        lambda x: n_ranges_nb(x, x+d+1),

        lambda x: create_ranges(x, x+d+1) # (from the dupe)

    ],

    labels=['nested-list-comp', 'n_ranges_nb', 'create_ranges'],

    n_range=[2**k for k in range(0, 18)],

    xlabel='N'

)

Are you interested to learn python concepts? Come and join the python course fast!

Related questions

0 votes
1 answer
asked Jul 22, 2019 in Python by Eresh Kumar (45.3k points)
0 votes
1 answer
0 votes
1 answer
asked Feb 17, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
2 answers

Browse Categories

...