Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Itertools cartesian product without order [duplicate]

EDIT: user2357112 correctly marked my question as a duplicate. The linked answer works for my question.

I'll leave this question up, since I think it is worded differently than the linked question and might help others get to the right place.


I would like to take the permutation between all of the indices in a list.

For example, for the list ['a', 'b', 'c'], I want to iterate over indices i and j so that I can compare 'a' with 'a', 'b', 'c', etc.

That's basically just two nested for loops, so product from itertools does the trick nicely.

But it's doing basically twice the work that I need it to. I just need the upper triangular (i, j) pairs (so, unordered pairs-- e.g. if (0,1) is iterated over, then (1,0) isn't needed).

I thought that would definitely be an already-answered thing, but I can't find it. Could you help to answer or, if this is a duplicate, point me in the right direction? Thanks!


What I have:

from itertools import product

exList = ['a', 'b', 'c']

for i,j in product(range(len(exList)), range(len(exList))):
    print([i,j])

---
Out:

[0, 0]
[0, 1]
[0, 2]
[1, 0]
[1, 1]
[1, 2]
[2, 0]
[2, 1]
[2, 2]

But that's twice the computation that I need, [0, 1] and [1, 0] are redundant, for example.

So the output of itertools is an ordered pair. I would like an unordered pair--like a triangular matrix.

What I would like:

from itertools import product

exList = ['a', 'b', 'c']

helpfulFunction(exList)

---
Out:

[0, 0]
[0, 1]
[0, 2]
[1, 1]
[1, 2]
[2, 2]
like image 911
julianstanley Avatar asked Oct 20 '25 16:10

julianstanley


1 Answers

Do an if statement and filter if j is greater or equals to i, only print then:

for i,j in product(range(len(exList)), range(len(exList))):
    if j >= i:
        print([i, j])

MUCH BETTER:

Use combinations_with_replacement:

for i, j in itertools.combinations_with_replacement(range(len(exList)), 2):
    print(i, j)

Both output:

[0, 0]
[0, 1]
[0, 2]
[1, 1]
[1, 2]
[2, 2]
like image 58
U12-Forward Avatar answered Oct 23 '25 04:10

U12-Forward