I cannot use itertools
So the coding seems pretty simple, but I'm having trouble thinking of the algorithm to keep a generator running until all iterations have been processed fully.
The idea of the function is to take 2 iterables as parameters like this ...
(['a', 'b', 'c', 'd', 'e'], [1,2,5])
And what it does is yield these values ...
a, b, b, c, c, c, c, c
However, in the event that the second iterable runs out of elements first, the function simply iterates the remaining value one time ...
So the remaining values would be iterated like this:
d, e
def iteration(letters, numbers):
times = 0
for x,y in zip(letters, numbers):
try:
for z in range(y):
yield x
except:
continue
[print(x) for x in iteration(['a', 'b', 'c', 'd'], [1,2,3])]
I'm having difficulty ignoring the first StopIteration and continuing to completion.
Use a default value of 1
for next so you print the letters at least once:
def iteration(letters, numbers):
# create iterator from numbers
it = iter(numbers)
# get every letter
for x in letters:
# either print in range passed or default range of 1
for z in range(next(it, 1)):
yield x
Output:
In [60]: for s in iteration(['a', 'b', 'c', 'd', 'e'], [1,2,5]):
....: print(s)
....:
a
b
b
c
c
c
c
c
d
e
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With