Skip to content Skip to sidebar Skip to footer

Invertable Cartesian Product Elements/index Translation Function

I have a problem where I need to identify the elements found at an indexed position within the Cartesian product of a series of lists but also, the inverse, i.e. identify the inde

Solution 1:

Imagine those combinations as two dimensional X-Y coordinates and use subscript to linear-index conversion and vice-verse. Thus, use NumPy's built-ins np.ravel_multi_index for getting the linear index and np.unravel_index for the subscript indices, which becomes your index_from_combination and combination_at_index respectively.

It's a simple translation and doesn't generate any combination whatsoever, so should be a breeze.

Sample run to make things clearer -

In[861]: np.ravel_multi_index((2,1),(3,2))
Out[861]: 5In[862]: np.unravel_index(5, (3,2))
Out[862]: (2, 1)

The math is simple enough to be implemented if you don't want to NumPy dependency for some reason -

defindex_from_combination(a, b):
    return b[0]*a[1] + b[1]

defcombination_at_index(a, b):
    d = b//a[1]
    r = b - a[1]*d
    return d, r

Sample run -

In[881]: index_from_combination([3,2],[2,1])
Out[881]: 5In[882]: combination_at_index([3,2],5)
Out[882]: (2, 1)

Post a Comment for "Invertable Cartesian Product Elements/index Translation Function"