jiahuiding jiahuiding - 1 month ago 6
Python Question

function that takes iterables and returns a string

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!

Answer

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
Comments