Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python array intersection efficiently

Tags:

python

I don't know how to make an intersect between these two arrays:

a = [[125, 1], [193, 1], [288, 23]]
b = [[108, 1], [288, 1], [193, 11]]

result = [[288,24], [193, 12]]

So the intersection is by the first element, the second element of the array is summed, any ideas how to do this efficiently?

Ok i made a mistake for not explaining what i mean about efficient, sorry. Consider the following naive implementation:

a = [[125, 1], [193, 1], [288, 23]]
b = [[108, 1], [288, 1], [193, 11]]
result = {}
for i, j in a:
    for k, l in b:
        if i == k:
            result[i] = j + l
print result

So i was trying to find a way to make more efficient solution to my problem, more pythonic in a way. So that's why i needed your help.

Try this test cases (my code is also on it):

Test Case

Running time: 28.6980509758

like image 562
badc0re Avatar asked Nov 29 '22 12:11

badc0re


2 Answers

result = []
ms, mb = (dict(a),dict(b)) if len(a)<len(b) else (dict(b),dict(a))
for k in ms:
  if k in mb:
    result.append([k,ms[k]+mb[k]])
like image 27
FUD Avatar answered Dec 06 '22 21:12

FUD


This data seems like it would be better stored as a dictionary

da = dict(a)
db = dict(b)

once you have it like that you can just:

result = [[k, da[k] + db[k]] for k in set(da.keys()).intersection(db.keys())]

or in python 2.7 you can also just use viewkeys instead of a set

result = [[k, da[k] + db[k]] for k in da.viewkeys() & db]
like image 58
cmd Avatar answered Dec 06 '22 20:12

cmd