Consider the following class definition: class TriangleNumber: def __init__(self, upper_limit): self.upper_limit = upper_limit def _iter__(self): return TriangleIterator(self.upper_limit) The TriangleNumber class provides a list of triangle numbers. The n-th triangle number is the total number of dots with n dots on each side of the triangle and is equal to the sum of the n natural numbers from 1 to n. The formula for the sum of n natural numbers from 1 to n is n* (n + 1) / 2. 1 3 6 10 15 For example, the following code fragment: number - TriangleNumber(5) for num in number: print(num, end = " ")
For example, the following code fragment: number = TriangleNumber(5) for num in number: print(num, end = " ") produces: 1 3 6 10 15 The above example contains a for loop to iterate through the iterable object i.e. TriangleNumber object) and prints the first 5 triangle numbers. Define the TriangleIterator class so that the for-loop above works correctly. The TriangleIterator class contains the following: • An integer data field named upper_limit that defines the upper limit value • An integer data field named current_number that defines the current value. The initial value is 1. • A constructor/initializer that that takes an integer, upper_limit, as a parameter and creates an iterator object. The_next__(self) method which returns the next element in the collection. 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 TriangleNumber class is given. For example: Test Result values = TriangleNumber(5) 1 for x in values: 3 print(x) 6 10 15
Consider the following class definition: class TriangleNumber: def __init__(self, upper_limit): self.upper_limit = upper
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
Consider the following class definition: class TriangleNumber: def __init__(self, upper_limit): self.upper_limit = upper
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!