def alternate(*args):
l = ''
c = 0
while True:
try:
iterable = args[c]
i = iter(iterable)
l = l + next(i)
c = c + 1
except:
break
yield l
The alternate generator takes any number of iterables as parameters: it produces the first value from the first parameter, then the first value from the second parameter, ..., then the first value from the last parameter; then the second value from the first parameter, then the second value from the second parameter, ..., then the second value from the last parameter; etc. If any iterable produces no more values, this generator produces no more values. For example:
for i in alternate('abcde','fg','hijk'):
print(i,end='')
the answer is:
afhbgic
when my function takes
('abcde','fg','hijk')
it returns
afh
but the correct answer is
afhbgic
can someone tell me how to fix it? many thanks!
What about solution like this:
def alternate(*args):
l = ''
# initialize iterators for each argument
iterators = [iter(it) for it in args]
# iterate over lengths, using iterators
while True:
for it in iterators:
try:
l = l + next(it)
except StopIteration:
return l
return l
result = alternate('abcde','fg','hijk')
print(result) # afhbgic
If you must have a generator, you can make use of itertools.zip_longest( izip_longest if using Python 2.x):
from itertools import zip_longest
def alternate(*args):
for tup in zip_longest(*args):
for el in tup:
if el:
yield el
else:
return
Output:
>>> ''.join(alternate('abcde','fg','hijk'))
'afhbgic'
>>>
Otherwise, just use a normal function:
from itertools import zip_longest
def alternate(*args):
s = ''
for tup in zip_longest(*args):
for el in tup:
if el:
s += el
else:
return s
Output:
>>> alternate('abcde','fg','hijk')
'afhbgic'
>>>
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