Consider the following class definition: class ArithmeticSequence: def _init__(self, common_difference = 1, max_value =
Posted: Sat May 14, 2022 2:49 pm
Consider the following class definition: class ArithmeticSequence: def _init__(self, common_difference = 1, max_value = 5): self.common_difference = common_difference self.max_value = max_value def _iter__(self): return ArithmeticIterator(self.common_difference, self.max_value) The ArithmeticSequence class provides a list of numbers, starting at 1, in an arithmetic sequence. In an Arithmetic Sequence the difference between one term and the next is a constant. For example, the following code fragment: sequence = ArithmeticSequence (3, 10) for num in sequence: print(num, end = " ") produces: 1 4 7 10 The above sequence has a difference of 3 between each number. The initial number is 1 and the last number is 10. The above example contains a for loop to iterate through the iterable object (i.e. ArithmeticSequence object) and prints numbers from the sequence. Define the ArithmeticIterator class so that the for-loop above works correctly. The ArithmeticIterator class contains the following: • An integer data field named common_difference that defines the common difference between two numbers. • An integer data field named current that defines the current value. The initial value is 1. • An integer data field named max_value that defines the maximum value of the sequence. A constructor/initializer that that takes two integers as parameters and creates an iterator object. • The _next__(self) method which returns the next element in the sequence. 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 ArithmeticSequence class is given. For example: Test Result 1 values = ArithmeticSequence(1, 5) for x in values: print(x) 2 3 4 5