Python: summation over all permutations

I'm stuck with a seemingly easy problem, can someone help?

I have two lists aand b. I can name the elements of the list a[i][j], where 0<i<100and 0<j<100.

I want to find everything a[i][j] - b[k][l]where 0<i<100, 0<j<100, 0<k<100and 0<l<100. And then do the summation over all the permutations i, j, k, l .

Does anyone know an elegant easy way to do this?

+4
source share
3 answers
import itertools
sum(a[i][j] - b[k][l] for i, j, k, l in itertools.product(range(1, 100), repeat=4))

itertools.productequivalent to a nested loop for. He will work on every tuple (i, j, k, l)from (1, 1, 1, 1)to (99, 99, 99, 99). This will skip the zero you seem to be asking for.

+3
source

:

(sum(map(sum, a)) - sum(map(sum, b))) * len(a) * len(b)

. O (n), , itertools, O (n ^ 2).

(edit: ), 100x100 , , .

, , , 100x100 0. , 100x100 , - 0 , :

from itertools import product

C = 100

def _sum(arr, a, b):
    return sum(arr[i][j] for i, j in itertools.product(range(a, b), repeat=2))

answer = (_sum(a, 1, C) - _sum(b, 1, C)) * (C-1)**2

, , . numpy, :

import numpy as np
A = np.array(a, np.int32)
B = np.array(b, np.int32)
answer = (np.sum(A[1:100, 1:100]) - np.sum(B[1:100, 1:100])) * 99**2
+2

Try generating Cartesian derivatives of the ranges of arrays to get indexes.

import itertools

cprod = itertools.product(range(1, 100, 1), range(1, 100, 1), range(1, 100, 1), range(1, 100, 1))
result = sum([a[cp[0]][cp[1] - b[cp[2]][cp[3] for cp in cprod])
0
source

All Articles