1
votes

I want to do a comparison between every pair of elements in the list without the following: DIFFERENCE=[1,2,3,4,5,6]

  1. no self comparisons
  2. no reverse comparisons

So the answer will be [1,2],[1,3],[1,4],[1,5],[1,6],[2,3],[4,5],[5,6],[3,4],[2,4],[2,5],[3,6],[2,6],[3,5],[4,6] I have written this so far but I was looking for a faster way.

for i in DIFFERENCE:
       for j in DIFFERENCE:
           if(some condition and i!=j and i+'_'+j not in COMPARISON and j+'_'+i not in COMPARISON):
               COMPARISON.append(i+'_'+j);
               COMPARISON.append(j+'_'+i);
               ANS_COUNT=ANS_COUNT+1;
2

2 Answers

6
votes

You should just use itertools.combinations:

>>> import itertools
>>> list(itertools.combinations([1,2,3,4,5,6], 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
0
votes

You can also do this using for loop:

l = list()
for i in range (1,7):
    for j in range (2,7):
        if(i == j):
            j = j + 1
        elif ((i,j) in l or (j,i) in l):
            continue
        else:
            l.append((i,j))

print l

output:

[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]