Home > database >  Calculating Cartesian product in Python
Calculating Cartesian product in Python

Time:09-27

There are 2 same arrays, A=np.array(['A','B','C']),B=np.array(['A','B','C']), I calculated the Cartesian product of A and B:

import numpy as np
from itertools import product
b=product(A,B)

the result of b is

[('A','A'),('A','B'),('A','C'),('B','A'),('B','B'),('B','C'),('C','A'),('C','B'),('C','C)]

In my project, the meaning of ('A','B') is the same as ('B','A'), How could I drop the duplications of b? I want to make b only reserve ('A','B'), ('A','C'), ('B','C'). Thanks!

CodePudding user response:

You can use combinations_with_replacement on a single array:

from itertools import combinations_with_replacement
list(combinations_with_replacement(A, r=2))

output:

[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

excluding self combinations:

from itertools import combinations
list(combinations(A, r=2))

output:

[('A', 'B'), ('A', 'C'), ('B', 'C')]
  • Related