Python Implementation of zip_longest with Deques and Fillvalue Handling

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to fill shorter input sequences until they reach the same length as the longest sequence. It uses `collections.deque` to efficiently handle sequences, and utilizes built-in functions such as `operator.itemgetter`, `functools.reduce`, `bisect.bisect_left`, and `math.ceil` to calculate and manipulate data.


Technology Stack : itertools, collections, operator, functools, bisect, math

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque
    from operator import itemgetter
    from functools import reduce
    from bisect import bisect_left
    from math import ceil

    def align_deques(deques):
        lengths = [len(d) for d in deques]
        max_length = max(lengths)
        return [deque.extend([fillvalue] * (max_length - len(d))) for d in deques]

    def split_deques(deques):
        for d in deques:
            while d and d[0] is fillvalue:
                d.popleft()
        return deques

    # Ensure all inputs are deques
    deques = [deque(args[i]) for i in range(len(args))]
    # Align all deques to the length of the longest
    deques = align_deques(deques)
    # Get the lengths of all deques
    lengths = [len(d) for d in deques]
    # Calculate the total length of the output
    total_length = sum(lengths)
    # Calculate the maximum number of elements per chunk
    chunk_size = ceil(total_length / len(deques))
    # Initialize the output list
    output = []
    # Iterate over chunks of the total length
    for i in range(0, total_length, chunk_size):
        # Get the chunk from each deque
        chunk = [d[i:i + chunk_size] for d in deques]
        # Split off the fillvalue chunks and re-align
        chunk = split_deques(chunk)
        # Convert the chunk to a list and append to output
        output.append(list(chunk))
    return output