Iterators and Generators Practice Problems

Important! These are all exam-level problems. Do not attempt these problems without a solid foundation in the subject and use them for exam practice.

1. Implement a generator function which takes a non-empty list that it is given and always gives back the current element of the list, looping back if necessary.

def neverending(l):
    """Implement this generator function which will never end, sequentially outputting the elements of the original list passed in.  
    >>>lst = ['h', 'i']
    >>>neverending(lst)
    h
    >>>neverending(lst)
    i
    >>>neverending(lst)
    h
    """"
    k = 0
    while True:
      yield lst[k]
    k += 1
    if k == len(lst):
      k = 0
def neverending(l):
    """Implement this generator function which will never end, sequentially outputting the elements of the original list passed in.  
    >>>lst = ['h', 'i']
    >>>neverending(lst)
    h
    >>>neverending(lst)
    i
    >>>neverending(lst)
    h
    """"
    "YOUR CODE HERE"
Toggle Solution

2. Suppose our Linked List class is being annoying and decides that it now wants to become an Iterator class. Below is the beginning of the implementation for the class.

class IteratorLinkedlist:
    class EmptyList:
        pass

    empty = EmptyList()

    def __init__(self, first, rest=empty):
        self.first = first
        self.rest = rest
        self.cur = self

Add any extra methods and their implementation in order to complete the Linked List class' transformation into an Iterator. Hint: What methods must be added?

"""Add as many methods to the above class to make it a working iterator. 
  >>>link = IteratorLinkedList(1, IteratorLinkedList(3))
  >>>next(link)
  1
  >>>next(link)
  3
  """

  def __next__(self):
      if self.cur == Linkedlist.empty:
          raise StopIteration
      else:
          result = self.curr.first
          self.cur = self.cur.rest
        return result

  def __iter__(self):
        return self

  Important: The key to this question was that you need both a __next__ and an __iter__ method to make it an iterator.
"""Add as many methods to the above class to make it a working iterator. 
    >>>link = IteratorLinkedList(1, IteratorLinkedList(3))
    >>>next(link)
    1
    >>>next(link)
    3
    """
    "YOUR CODE HERE"
Toggle Solution