2

I'm trying to write a nested loop that prints out all possible "unique pairs" of numbers from a certain range. For example, if the range was from 1 to 3 the unique pairs would be:

(1,2) (1,3) (2,3)

If the range was from 1 to 4 the unique pairs would be:

(1,2) (1,3) (1,4) (2,3) (2,4) (3,4)

Here's how I did it for 1 to 3:

for i in range(1,4):
    for j in range(2,4):
        if (i != j & j != (i-1)):
            print (i,j)

which prints out (1, 2), (1, 3),(2, 3). But this is a hack because it doesn't work when I change the range to 1,5. It prints out duplicate pairs such as (1,5) and (5,1).

5 Answers 5

10

Use itertools.combinations():

>>> import itertools
>>> print list(itertools.combinations(range(1, 5), r=2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

As long as your inputs are unique, there will be no repeated combinations:

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.

Sign up to request clarification or add additional context in comments.

Comments

10
for i in range(1,4):
    for j in range(i+1,4):  # <-- the key is to make j start at i+1
        print (i,j)

Comments

6

You are probably looking for something like this:

n = 4
x = [(i,j) for i in range(1,n+1) for j in range(i+1, n+1)]
print x

Cheers, Alex

4 Comments

Why n+1? Isn't n+1 just 5? Maybe I'm misunderstanding something here?
You need n+1 because range (i, j) goes from i to j - 1. So if we used (1, n) we would have 1 to n - 1. So if n was 4, then we would be missing 4, we would only have 1, 2 and 3.
@AlexandruGodri I think he is asking why not replace all n+1's with 5's.
Because i wrote it for a general purpose. You just change the "n" to whatever and the code works :)
6

You can use itertools.combinations:

>>> from itertools import combinations
>>> print list(combinations(range(1,4), 2))
[(1, 2), (1, 3), (2, 3)]

Python 2 Documentation

Python 3 Documentation

Comments

4

See itertools module.

Maybe what you want is

list(itertools.combinations(range(1,4),2)) == [(1, 2), (1, 3), (2, 3)]

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.