Key Word(s): Generators, Memeory layouts



Exercise 1

Do the following exercise in a .py file called sentence.py.

Create a Sentence iterator class that uses a generator.

Notes and Hints:

  • You will write the generator in the __iter__ special method.
  • The generator automatically gets __next__ (no need to implement it).
  • Now you only need to create a single class.

Here's the sentence iterator class that we've been using:

class SentenceIterator:
    def __init__(self, words): 
        self.words = words 
        self.index = 0

    def __next__(self): 
        try:
            word = self.words[self.index] 
        except IndexError:
            raise StopIteration() 
        self.index += 1
        return word 

    def __iter__(self):
        return self

class Sentence: # An iterable
    def __init__(self, text): 
        self.text = text
        self.words = text.split()

    def __iter__(self):
        return SentenceIterator(self.words)

    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)