Skip to content

Instantly share code, notes, and snippets.

@Stefano314
Last active June 19, 2022 14:44
Show Gist options
  • Save Stefano314/ad0056ada66510042913174cab226c27 to your computer and use it in GitHub Desktop.
Save Stefano314/ad0056ada66510042913174cab226c27 to your computer and use it in GitHub Desktop.
Fast way to get the combination pair list of the elements in a list.
import numpy as np
def fast_combinations(row : list, self_loops = False) -> np.array:
"""
Description
-----------
Fast way to obtain the combination of all the elements inside a list using Numpy.
Self connections are present.
Parameters
----------
row : list
List of elements to combine.
self_loops : bool, optional
Specify if self connections are required.
The default values is 'False'.
Return
------
np.array : Array containing all the combination pairs of the given elements.
NOTE
----
Pay attention to the NANS entries.
- If you use 'np.nan' as float then the function won't be able to remove it and that value will
also be used in the combination (longer processing time). Also, it won't remove np.nan self loops, since np.nan != np.nan.
- None are supported, so if there is a None in the list it will be removed.
- 'nan' strings are used too, because numpy arrays that have strings will convert np.nan to 'nan'.
"""
if isinstance(row, list):
row = [val for val in row if val is not None]
else:
row = row.tolist()
row = [val for val in row if val is not None]
try:
if self_loops:
comb = np.unique(np.sort(np.array(np.meshgrid(row, row)).T.reshape(-1,2)), axis=0)
else:
comb = np.unique(np.sort(np.array(np.meshgrid(row, row)).T.reshape(-1,2)), axis=0)
comb = np.delete(comb, np.where(comb[:,0] == comb[:,1]), axis=0)
comb = np.delete(comb, np.where(comb[:,1] == 'nan'), axis=0)
if len(comb) == 0:
return [[None, None]]
return comb
except:
return [[None, None]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment