def permutation(l, index):
    l = sorted(l)
if not index:
    return l
counter = Counter(l)
total_count = count_permutations(counter)
acc = 0
for i, v in enumerate(l):
    if i > 0 and v == l[i - 1]:
        continue
count = total_count * counter[v] / len(l)
if acc + count > index:
    return [v] + permutation(l[:i] + l[i + 1:], index - acc)
acc += count
raise ValueError('Not enough permutations')
Algorithm for finding multiset permutation given lexicographic index