Skip to content

Instantly share code, notes, and snippets.

@Miladiouss
Last active September 13, 2018 22:33
Show Gist options
  • Save Miladiouss/874817b1a6f7caaa1abd71e90ccf0094 to your computer and use it in GitHub Desktop.
Save Miladiouss/874817b1a6f7caaa1abd71e90ccf0094 to your computer and use it in GitHub Desktop.
Given a (flattened) list of lists, which element of which list does i correspond to?
def index_of_which_bin(bin_sizes, absolute_index, verbose=False):
"""
Given the absolute index, returns which bin it falls in and which element of that bin it corresponds to.
"""
# Which class/bin does i fall into?
accum = np.add.accumulate(bin_sizes)
if verbose:
print("accum =", accum)
bin_index = len(np.argwhere(accum <= absolute_index))
if verbose:
print("class_label =", bin_index)
# Which element of the fallent class/bin does i correspond to?
index_wrt_class = absolute_index - np.insert(accum, 0, 0)[bin_index]
if verbose:
print("index_wrt_class =", index_wrt_class)
return bin_index, index_wrt_class
# Example
index_of_which_bin(bin_sizes = [10, 20, 30, 100], absolute_index = 15, verbose = True)
@Miladiouss
Copy link
Author

Consider the following list of lists:

l = [[11, 12, 13], [21, 22, 23, 24], [31, 32]]
l_flat = [11, 12, 13, 21, 22, 23, 24, 31, 32]
lengths = [3, 4, 2]

Counting from 0, the 4th part of l_flat is 1st part of the 1st list. Hence, index_of_which_bin(lengths, 4) will output 1, 1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment