Skip to content

How to create Interleaving Arrays in Python

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([]) == []
Code language: JavaScript (javascript)

The solution in Python code

Option 1:

from itertools import chain, zip_longest def interleave(*args): return list(chain.from_iterable(zip_longest(*args)))
Code language: Python (python)

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
Code language: Python (python)

Option 3:

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

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([]), [])
Code language: Python (python)

See also  How to Generate a Random String in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x