2

I'm writing a generator that takes an iterable and an integer n. For example if I call my generator:

generator('abcdefg',2)

then it should yield a, d, g skipping 2 letters.

When I call iter(iterable) then use yield next the yield automatically skips 1 letter. How would I tell python to skip yielding so I can skip n letters?

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
VN1992
  • 121
  • 1
  • 3
  • 7

4 Answers4

3

Your generator is effectively islice with a step parameter, so you could wrap the original iterable as such:

from itertools import islice

def generator(iterable, skip):
    return islice(iterable, None, None, skip+1)

for item in generator('abcdefg', 2):
    print(item)
# a
# d
# g

If you wanted to write it by hand, then perhaps a simple way to understand is first yield'ing from the iterable, then consuming from the iterable the gap size...

def generator(iterable, skip):
    it = iter(iterable)
    while True:
        yield next(it)
        for _ in range(skip):
            next(it)
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
2

This might be what you want

def generator(string, skip):
    for i,c in enumerate(string):
        if i % (skip+1)==0:
            yield c

This doesn't actually "skip" yield statements, that is every yield is executed. However, yield is only called at fixed intervals of the iteration over string characters.

Jon Rifkin
  • 21
  • 3
0

The basic framework using a custom iterator:

class skipper():
    def __init__(self, iterable, skip_count):
        self.it = iter(iterable)
        self.skip = skip_count
    def __iter__(self):
        return self
    def __next__(self):
        value = next(self.it)
        for _ in range(self.skip):
            next(self.it, None)
        return value

You could easily add any other behaviour you needed to this class.

Community
  • 1
  • 1
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
0

You can do this by simply using next() function

def make_generator():
    for x in range(1, 10):
        yield x


my_generator = make_generator()


def generator(temp_generator, num):  # generator('abcdefg',2)
    for x in range(num):
        next(temp_generator)
    for y in temp_generator:
        print(y)  # Skipped Value of generator
generator(my_generator, 2)

Output: 3 4 5 6 7 8 9

Anurag Misra
  • 1,516
  • 18
  • 24