Question
Question text Iterators provide a systematic way to access all of the elements in a collection. To define an iterator, we need to add the
Question text
Iterators provide a systematic way to access all of the elements in a collection. To define an iterator, we need to add the __iter__() method to the class that we want to iterator over. For example, we could define an __iter__() method for the LinkedList class as follows:
def __iter__(self): return LinkedListIterator(self.head)
This passes the "head" reference to an object of type LinkedListIterator. The LinkedListIterator class must contain the definition of the two methods:
__init__() __next__()
The __next__() method is called repeatedly when a collection is being iterated over, and each time it is called, it returns the next value in the collection.
For this task you can assume that the Node class, and the LinkedList class are provided. You do not need to inclue these classes in your answer. The LinkedList class contains the special __iter__() method defined as shown above. You need to define the LinkedListIterator class. This class will have the following structure:
class LinkedListIterator: def __init__(self, head): def __next__(self):
Reminder: when there are no more elements to iterate over, the __next__() method must raise a StopException.
For example:
Test | Result |
---|---|
values = LinkedList() values.add('cherry') values.add('banana') values.add('apple') for v in values: print(v) | apple banana cherry |
values = LinkedList() values.add(1) values.add(2) values.add(3) for v in values: print(v) | 3 2 1 |
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started