Not necessarily O (1), but the following should be very fast:
Take the source combination algorithm:
def combinations(elems, m): #The k-th element depends on what order you use for #the combinations. Assuming it looks something like this... if m == 0: return [[]] else: combs = [] for e in elems: combs += combinations(remove(e,elems), m-1)
For n initial elements and m combination lengths, we have n!/(nm)!m! complete combinations. We can use this fact to go directly to our desired combination:
def kth_comb(elems, m, k): #High level pseudo code #Untested and probably full of errors if m == 0: return [] else: combs_per_set = ncombs(len(elems) - 1, m-1) i = k / combs_per_set k = k % combs_per_set x = elems[i] return x + kth_comb(remove(x,elems), m-1, k)
source share