开发者

Removing nested loops in numpy

I've been writing a program to brute force check a sequence of numbers to look for euler bricks, but the method that I came up with involves a triple loop. Since nested Python loops get notoriously slow, I was wondering if there was a better way using numpy to create the array of values that I need.

#x=max side length of brick. User Input.    
for t in range(3,x):
    a=[];b=[];c=[];
    for u in range(2,t):
        for v in range(1,u):
                a.append(t)
                b.开发者_StackOverflow社区append(u)
                c.append(v)
    a=np.array(a)
    b=np.array(b)
    c=np.array(c)
    ...

Is there a better way to generate the array af values, using numpy commands?

Thanks.

Example: If x=10, when t=3 I want to get:

a=[3]  
b=[2]     
c=[1]

the first time through the loop. After that, when t=4:

a=[4, 4, 4]
b=[2, 3, 3]
c=[1, 1, 2]

The third time (t=5) I want:

a=[5, 5, 5, 5, 5, 5]
b=[2, 3, 3, 4, 4, 4]
c=[1, 1, 2, 1, 2, 3]

and so on, up to max side lengths around 5000 or so.

EDIT: Solution

a=array(3)
b=array(2)
c=array(1)
for i in range(4,x): #Removing the (3,2,1) check from code does not affect results.
    foo=arange(1,i-1)
    foo2=empty(len(foo))
    foo2.fill(i-1)
    c=hstack((c,foo))
    b=hstack((b,foo2))
    a=empty(len(b))
    a.fill(i)
    ...

Works many times faster now. Thanks all.


Try to use .empty and .fill (http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.fill.html)


There are couple of things which could help, but probably only for large values of x. For starters use xrange instead of range, that will save creating a list you never need. You could also create empty numpy arrays of the correct length and fill them up with the values as you go, instead of appending to a list and then converting it into a numpy array.

I believe this code will work (no python access right this second):

for t in xrange(3, x):
    size = (t - 2) * (t - 3)
    a = np.zeros(size)
    b = np.zeros(size)
    c = np.zeros(size)

    idx = 0
    for u in xrange(2,t):
        for v in xrange(1,u):
            a[idx] = t
            b[idx] = u
            c[idx] = v
            idx += 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜