简体   繁体   English

Python中二维数组子部分的总和

[英]Sum of 2d array subsection in Python

Here is a task description: I have 2d array NxM, N, M<1000, and there are K(K<100000) sets of coordinates(x1, x2, y1, y2). 这是一个任务说明:我有2d数组NxM,N,M <1000,并且有K(K <100000)个坐标集(x1,x2,y1,y2)。 I need to sum all the elements in rectangle(x1, x2, y1, y2). 我需要对矩形(x1,x2,y1,y2)中的所有元素求和。
My code works but I need make it faster cause the largest tests dont work in required time. 我的代码有效,但是我需要使其速度更快,因为最大的测试无法在所需的时间内起作用。

Here it is: 这里是:

def build_y(cx, fx, lx, cy, fy, ly):
    if fy == ly:
        if fx == lx:
            t[cx][cy] = a[fx][fy]
        else:
            t[cx][cy] = t[cx*2][cy] + t[cx*2+1][cy];
    else:
        my = int((fy + ly) / 2)
        build_y (cx, fx, lx, cy*2, fy, my)
        build_y (cx, fx, lx, cy*2+1, my+1, ly)
        t[cx][cy] = t[cx][cy*2] + t[cx][cy*2+1]

def build_x(cx, fx, lx):
    if fx != lx:
        mx = int((fx + lx) / 2)
        build_x (cx*2, fx, mx)
        build_x (cx*2+1, mx+1, lx)
    build_y (cx, fx, lx, 1, 0, m-1)

def sum_y (cx, cy, tfy, tly, fy, ly):
    if fy > ly:
        return 0
    if fy == tfy and tly == ly:
        return t[cx][cy]
    tmy = int((tfy + tly) / 2)
    return sum_y(cx, cy*2, tfy, tmy, fy, min(ly, tmy)) + sum_y(cx, cy*2+1, tmy+1, tly, max(fy, tmy+1), ly)
def sum_x(cx, tfx, tlx, fx, lx, fy, ly):
    if fx > lx:
        return 0
    if fx == tfx and tlx == lx:
        return sum_y(cx, 1, 0, m-1, fy, ly)
    tmx = int((tfx + tlx) / 2)
    return sum_x(cx*2, tfx, tmx, fx, min(lx, tmx), fy, ly) + sum_x(cx*2+1, tmx+1, tlx, max(fx, tmx+1), lx, fy, ly)
fin = open('input.txt', 'r').read().split()
n = int(fin[0])
m = int(fin[1])
k = int(fin[2])
a = []
b = []
t = [0]*3*n
for i in range(3*n):
    t[i] = [0]*3*m
for i in range(n):
    a.append([int(j) for j in fin[3+i*m:3+i*m+m]])
build_x(1, 0, n-1)
for i in range(k):
    b.append([int(j) for j in fin [3+n*m+4*i:3+n*m+4*i+4]])
for i in range(k):
    print(sum_x(1, 0, n-1, b[i][0]-1, b[i][2]-1, b[i][1]-1, b[i][3]-1))

use numpy and rewrite all the lists as numpy arrays, for example t[cx][cy] = a[fx][fy] becomes t[cx,cy] = a[fx,fy] after you have initialized t, a as numpy arrays. 使用numpy并将所有列表重写为numpy数组,例如t[cx,cy] = a[fx,fy]初始化t, a之后t[cx,cy] = a[fx,fy] t[cx][cy] = a[fx][fy]变为t[cx,cy] = a[fx,fy] numpy数组。 You can simply get a factor 100 of speed-up. 您可以简单地将速度提高100倍。 In fact, the numpy operations are much faster than list operations, so if you have a lot of them the use of numpy is very suitable. 实际上,numpy操作比list操作要快得多,因此,如果您有很多操作,那么使用numpy非常适合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM