How to create Interleaving Arrays in Python

0 min read 191 words

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:

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:

from itertools import chain, zip_longest

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

Option 2:

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:

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

Test cases to validate our solution

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([]), [])
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags