The challenge

Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed-in arguments. If one of them is shorter than the others, the result should be padded with empty elements.

Examples:

1
2
3
4
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 solution in Python code

Option 1:

1
2
3
4
from itertools import chain, zip_longest

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

Option 2:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def interleave(*args):
    max_len = max(map(len,args))
    interleaved = []
    for i in range(max_len):
        for arr in args:
            if i < len(arr):
                interleaved.append(arr[i])
            else:
                interleaved.append(None)
    return interleaved

Option 3:

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

Test cases to validate our solution

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