Indexing itertools permutations without unpacking the intertool object

22 views Asked by At

I have the following

from itertools import islice, permutations

# Function to get a chunk of the itertools object
def get_chunk(iterator, chunk_size):
    return list(islice(iterator, chunk_size))

# Example usage
sequence = [1, 2, 3, 4]
chunk_size = 10  # Define your chunk size here
permutations_iterator = permutations(sequence)
chunk = get_chunk(permutations_iterator, chunk_size)

# Assuming the chunk has at least two elements
if len(chunk) > 1:
    first_element = chunk[0]
    last_element = chunk[-1]
elif len(chunk) == 1:
    first_element = last_element = chunk[0]
else:
    first_element = last_element = None

print("First element of the chunk:", first_element)
print("Last element of the chunk:", last_element)

I wanto to get the first and the last permutation of each chunk without unpacking them in lists for avoiding memory issues. Is there a way?

I wanted to get lists of permutations where for each chunk i have the first and the last permutation of the itertool object without necessarely unpack the itertool object.

1

There are 1 answers

0
Stef On

It's possible to compute the nth permutation directly for a particular value of n without computing all the intermediary permutations.

This is implemented in function nth_permutation of library more_itertools.

from more_itertools import nth_permutation
from math import factorial

sequence = [1,2,3,4]
chunk_size = 10

number_of_permutations = factorial(len(sequence))

print(*(
    (nth_permutation(sequence, len(sequence), i), nth_permutation(sequence, len(sequence), min(i+chunk_size-1, number_of_permutations-1)))
    for i in range(0, number_of_permutations, chunk_size)
),sep='\n')
# ((1, 2, 3, 4), (2, 3, 4, 1))
# ((2, 4, 1, 3), (4, 1, 3, 2))
# ((4, 2, 1, 3), (4, 3, 2, 1))