Tuesday, April 23, 2024
HomeSoftware EngineeringThe best way to create Interleaving Arrays in Python

The best way to create Interleaving Arrays in Python


The problem

Create a operate, that accepts an arbitrary variety of arrays and returns a single array generated by alternately appending components from the passed-in arguments. If certainly one of them is shorter than the others, the outcome needs to be padded with empty components.

Examples:

interleave([1, 2, 3], ["c", "d", "e"]) == [1, "c", 2, "d", 3, "e"]
interleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, None]
interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9]
interleave([]) == []

The answer in Python code

Possibility 1:

from itertools import chain, zip_longest

def interleave(*args):
    return record(chain.from_iterable(zip_longest(*args)))

Possibility 2:

def interleave(*args):
    max_len = max(map(len,args))
    interleaved = []
    for i in vary(max_len):
        for arr in args:
            if i < len(arr):
                interleaved.append(arr[i])
            else:
                interleaved.append(None)
    return interleaved

Possibility 3:

interleave=lambda *a:sum([list(i) for i in __import__('itertools').zip_longest(*a)],[])

Take a look at circumstances to validate our answer

check.assert_equals(interleave([1, 2, 3], ["c", "d", "e"]), [1, "c", 2, "d", 3, "e"])
check.assert_equals(interleave([1, 2, 3], [4, 5]), [1, 4, 2, 5, 3, None])
check.assert_equals(interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]), [1, 4, 7, 2, 5, 8, 3, 6, 9])
check.assert_equals(interleave([]), [])
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments