Question: Please write the functions in python and include explanations and screenshots An iterator is a convenient pattern for traversing over all of the elements in
Please write the functions in python and include explanations and screenshots
An iterator is a convenient pattern for traversing over all of the elements in some collection (such as a list, string, tuple, etc...). Consider the following example:
values = SquareNumber(5) for value in values: print(value)
The above example iterates five square numbers : i.e. 1, 4, 9, 16, 25. Note: a square number is one which has a whole square root, such as 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, etc. The SquareNumber class is iterable, i.e. it contains an __iter__() method which returns an iterator object so that we can then use a for loop to iterate through the iterable object.
Question 1a):
Define a class named SquareNumberIterator so that the for-loop above works correctly and it must contain the following:
- A private integer field named __current that defines the current number which is used to generate a square number.
- A private integer field named __count that defines the number of square numbers needed.
- A constructor/initializer that creates an iterator object.
- The __next__(self) method which returns the next square number in the collection. If there are no more elements (in other words, if the traversal has finished) then a StopIteration exception is raised.
| Test | Result |
for number in SquareNumber(5): print(number) | 1 4 9 16 25 |
for number in SquareNumber(4): print(number) | 1 4 9 16 |
Question 1b):
Continuing on from the previous question, define a class named LinkedListIterator to represent a linked list iterator so that we can use a for loop to iterate through the elements in a linked list. The LinkedListIterator class contains the following:
- A private field named __current that defines the current node in a linked list.
- A constructor/initializer that takes a Node object as a parameter and creates an iterator object
- The __next__(self) method which returns the next element in the linked list. If there are no more elements (in other words, if the traversal has finished) then a StopIteration exception is raised.
-
Note: you can assume that the Node class, and the LinkedList class are given and the __iter__(self) method is provided in the implementation.
def __iter__(self): return LinkedListIterator(self.__head)
| Test | Result |
values = LinkedList() values.add('cherry') values.add('banana') values.add('apple') for value in values: print(value) | apple banana cherry |
values = LinkedList() values.add(1) values.add(2) values.add(3) for value in values: print(value) | 3 2 1 |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
