Question

Iterators provide a systematic way to access all of the elements in a collection. To define...

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 over which we want to iterate.

Consider the following lines of code:

  odd_numbers = Odds(9)
  for num in odd_numbers:
      print(num)

This code iterates over all the odd numbers less than or equal to 9 starting from the number 1. It assumes that the Odds class is iterable, i.e., it contains an __iter__() method which returns an Iterator object. In this exercise, the Iterator object is an instance of the OddsIterator class and the OddsIterator class must contain the definition of the two methods:

__init__()
__next__()

The __next__() method will be called repeatedly when a collection is being iterated over, and each time it is called, it returns the next value in the collection.

Define two classes: the Odds class and the OddsIterator class so that the for loop above works correctly. The skeleton of the two classes is shown below:

class Odds:
    def __init__( ... ):
        #Stores the number to be reached
    def __iter__(self):
        #Returns an instance of the OddsIterator class

class OddsIterator:
    def __init__(self, upper):
        #Stores the information needed to do the iteration
    def __next__(self):
        #Returns the next number in the iteration
        #raises a StopIteration when there are no more elements

For example:

Test Result
o = Odds(9)
for i in o:
    print(i)
1
3
5
7
9
o = Odds(1)
for i in o:
    print(i)
1
0 0
Add a comment Improve this question Transcribed image text
Answer #1
class Odds:
    def __init__(self, max_value):
        self.max_value = max_value

    def __iter__(self):
        return OddsIterator(self)


class OddsIterator:
    def __init__(self, upper):
        self.current = 1
        self.upper = upper.max_value

    def __next__(self):
        if self.current <= self.upper:
            result = self.current
            self.current += 2
            return result
        else:
            raise StopIteration

Add a comment
Know the answer?
Add Answer to:
Iterators provide a systematic way to access all of the elements in a collection. To define...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Question A matrix of dimensions m × n (an m-by-n matrix) is an ordered collection of m × n elemen...

    Question A matrix of dimensions m × n (an m-by-n matrix) is an ordered collection of m × n elements. which are called eernents (or components). The elements of an (m × n)-dimensional matrix A are denoted as a,, where 1im and1 S, symbolically, written as, A-a(1,1) S (i.j) S(m, ). Written in the familiar notation: 01,1 am Gm,n A3×3matrix The horizontal and vertical lines of entries in a matrix are called rows and columns, respectively A matrix with the...

  • 10p Python For the following question, refer to the Python module on the right, as well...

    10p Python For the following question, refer to the Python module on the right, as well as the code below. 1) What is the output of the following code? #dodgeable.py #main dodgeable.py import dodgeable class Locatable: def NUM_CARS = 3 init (self,x,y): NUM TRUCKS = 2 self.mX = X WIDTH = 60 self.mY = y def setx (self,x): def main (): self.mX = x object_list = [] def sety (self, y): self.mY = y for i in range (NUM_CARS) :...

  • Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support...

    Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support the Iterable interface such that the following code works: JstyArray<Integer> data; data = new JstyArray<Integer>(10); for (int i = 0; i < 10; ++i) { data.set(i, new Integer(i) ); } int sum = 0; for ( int v : data ) { if (v == null) continue; // empty cell sum += v; } The iterator provided by this class follows the behaviour of...

  • python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in...

    python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in addition to being a regular dictionary (using inheritance), it also defines an auxiliary/attribute dictionary that uses the bidict’s values as keys, associated to a set of the bidict’s keys (the keys associated with that value). Remember that multiple keys can associate to the same value, which is why we use a set: since keys are hashable (hashable = immutable) we can store them in...

  • PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None   

    PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None        self.__size = 0    # Return the head element in the list    def getFirst(self):        if self.__size == 0:            return None        else:            return self.__head.element        # Return the last element in the list    def getLast(self):        if self.__size == 0:            return None        else:            return self.__tail.element    # Add an element to the beginning of the list    def addFirst(self, e):        newNode = Node(e) # Create a new node        newNode.next = self.__head # link...

  • # Problem 3 def printexp(tree): sVal = "" if tree: sVal = '(' + printexp(tree.getLeftChild()) sVal = sV...

    # Problem 3 def printexp(tree): sVal = "" if tree: sVal = '(' + printexp(tree.getLeftChild()) sVal = sVal + str(tree.getRootVal()) sVal = sVal + printexp(tree.getRightChild())+')' return sVal #### Functions and classes to help with Homework 6 #### You should not make any changes to the functions and classes in this file, #### but you should understand what they do and how they work. import sys ### This function will be re-defined in hw6.py. However, it is needed for ExpTree, ###...

  • In this part, you will complete the code to solve a maze.

    - Complete the code to solve a maze- Discuss related data structures topicsProgramming-----------In this part, you will complete the code to solve a maze.Begin with the "solveMaze.py" starter file.This file contains comment instructions that tell you where to add your code.Each maze resides in a text file (with a .txt extension).The following symbols are used in the mazes:BARRIER = '-' # barrierFINISH = 'F' # finish (goal)OPEN = 'O' # open stepSTART = 'S' # start stepVISITED = '#' #...

  • Create a linked list with given code Given code: import java.util.Iterator; public interface Set { /**...

    Create a linked list with given code Given code: import java.util.Iterator; public interface Set { /** Removes all of the elements from this set */ void clear(); /** Returns true if this set contains no elements @return true if this set contains no elements */ boolean isEmpty(); /** Returns the number of elements in this set (its cardinality) @return the number of elements in this set */ int size(); /** Returns an iterator over the elements in this set @return...

  • Please answer all the questions 2. Design two programs named BaseClass and SubClass. In BaseClass, define...

    Please answer all the questions 2. Design two programs named BaseClass and SubClass. In BaseClass, define a variable xVar (type: char, value: 65), and a method myPrint to print xVar. SubClass is a subclass of BaseClass. In SubClass, define a variable yVar (type: int, value: 16) and another variable strVar (type: String, value: "java program!"). There is also a method myPrint to print the value of yVar and strVar in SubClass, as well as an additional method printAll, in which...

  • Python3 : question about object-oriented programming, Please write program in the template(critter.py),specific information is on the graphs the missing words in the 4th line are 'To save an attri...

    Python3 : question about object-oriented programming, Please write program in the template(critter.py),specific information is on the graphs the missing words in the 4th line are 'To save an attribute, attach it to this self keyword' W11 - Critters Implement the Critter class. Each critter C has attributes species, size, and age The constructor accepts arguments for the attributes above, in the order above. You can expect size and age to be numeric values Each critter C has a can_eat) method,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT