1

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 Answers 2

6

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)]
Sign up to request clarification or add additional context in comments.

3 Comments

Hi I was wondering if you can give me some insights into why I am getting the following error when I run : TMP_DIFF=[list(i) for i in list(itertools.combinations(DIFFERENCE2, 2))]; MemoryError. Atfirst, I thought may be len(DIFFERENCE2) =0,1,2 was a problem so I wrote,if(len(DIFFERENCE2)>2):TMP_DIFF=[list(i) for i in list(itertools.combinations(DIFFERENCE2, 2))];but the error this persists. Please comment.
@mparida: How big is DIFFERENCE2? If it's more than a few tens of thousands of entries long, you'll run out of memory constructing every possible combination. In that case, consider iterating over the itertools.combinations output directly, which will "lazily" generate the combinations for you.
Thanks for quick reply nneonneo I am not sure how big is DIFFERENCE2 but like you said I am assuming it is pretty big to flag such an error. I am not sure if I understand the last line In that case, consider iterating over the itertools.combinations output directly, which will "lazily" generate the combinations for you..please explain. Appreciate it.
0

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.