0
def yield_and_skip(iterable,skip):
    for i in iterable:
        print(skip(i))
        for x in range(skip(i)):
            pass
        yield i

I'm defning a function called skip_yield, which produces a value from the iterable but then it then skips the number of values specified when the function argument is called on the just-produced value. It takes 2 parameters: skip is a small function. However, if I try to do this:

print(''.join([v for v in yield_and_skip('abbabxcabbcaccabb',lambda x : {'a':1,'b':2,'c':3}.get(x,0))]))

it gives me:

abbabcabbcaccabb

but it should give me:

abxccab

Any idea?

3
  • 1
    What's the point of having a loop with empty body (pass) here? Commented Apr 28, 2016 at 16:45
  • Can you please share the yield_and_skip function? Commented Apr 28, 2016 at 16:57
  • Please don't deface your questions. Commented Apr 28, 2016 at 17:06

2 Answers 2

3

First of all, pass doesn't do anything to iterable. If you need to advance the iterator, call the next function on iterator object skip(i) number of times (either directly or indirectly).

Also, next call may raise StopIteration, thus terminating the loop. yield i before advancing the iterator or provide the second argument, to make next swallow the exception.

Your code would look like

def yield_and_skip(iterable, skip):
    it = iter(iterable)
    for i in it:
        for _ in range(skip(i)):
            next(it, None)
        yield i
Sign up to request clarification or add additional context in comments.

1 Comment

"yield i before advancing the iterator" is not necessary and next(it) should be next(it, None)
2

You could define a counter for the number of elements to skip and update it accordingly

def yield_and_skip(iterable,skip):
    num_to_skip = 0
    for i in iterable:
        if num_to_skip == 0:
            num_to_skip = skip(i)
            yield i
        else:
            num_to_skip -= 1

The output of your sample line is

>>> print(''.join([v for v in yield_and_skip('abbabxcabbcaccabb',lambda x : {'a':1,'b':2,'c':3}.get(x,0))]))
abxccab

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.