#92 · Iterators and generators · Intermediate · 75 XP · about 14 min
Write a generator interleave(*iterables) that takes any number of iterables and yields their items in turns: the first item of each, in order, then the second item of each, and so on. When one runs out, skip it and keep taking turns among the rest until all of them are used up.
It must be lazy: it takes an item from a source only when that item is needed, so it also works when some sources never end.
list(interleave([1, 2, 3], 'ab')) # returns [1, 'a', 2, 'b', 3] list(interleave('AB', [], 'xyz')) # returns ['A', 'x', 'B', 'y', 'z'] list(interleave()) # returns [] from itertools import count, islice list(islice(interleave(count(), 'hi'), 6)) # returns [0, 'h', 1, 'i', 2, 3]
NoneReady?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.