Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicate interaction pairs in python sets

Tags:

python

tuples

set

suppose you have a list of tuples in a python set:

>>> pairs = set( [(0,1),(0,1),(1,0)] )
>>> print pairs
set([(0, 1), (1, 0)])

Obviously, the first two elements are duplicates and according to the definition of a set, "pairs" only holds unique elements.

However, in my particular case the tuple (i,j) defines an interaction pair. Thus, (i,j) and (j,i) are the same. I need an effective way to reduce all duplicate elements. Computation time is crucial for me since the total set could easily contain a number of element as large as 10**6. I expect the following result:

>>> pairs = set( [(0,1),(0,1),(1,0)] )
>>> pairs = remove_duplicate_interactions(pairs)
>>> print pairs
set([0,1]) or set([1,0])

I am thankful for any hint.

Edit:

Someone asked about the context. This is supposed to be used for particle simulations. Due to symmetry conditions, the force of particle i acting on j is the same as the force of j acting on i. The reduction of computation time is thus 50 %.

like image 531
Rakulan S. Avatar asked Feb 29 '12 16:02

Rakulan S.


1 Answers

How about:

In [4]: pairs = set( [(0,1),(0,1),(1,0),(1,2),(1,0),(2,1)] )

In [5]: set((a,b) if a<=b else (b,a) for a,b in pairs)
Out[5]: set([(0, 1), (1, 2)])
like image 104
NPE Avatar answered Sep 21 '22 12:09

NPE