I am writing a small class 'AP' ('Arithmetic Progression') for my school assignment. I have included an option for making the AP infinitely long.
class AP:
def __init__(self, first_term: float, co_diff: float, n: int = inf) -> None:
self.a1 = first_term
self.d = co_diff
self.term = 0
self.n = n
def __repr__(self) -> str:
return f'AP({self.a1}, {self.d}, {self.n})'
def __str__(self) -> str:
output_str = f"{', '.join([str(term) for term in list(self.terms(term=6))])}, ...."
if self.n != inf:
return output_str + f', {(self.a1 + ((self.n - 1) * self.d))}'
return output_str
def terms(self, term: int):
return AP(self.a1, self.d, n=term)
def __iter__(self):
return self
def __next__(self):
self.term += 1
if self.term < self.n:
return (self.a1 + ((self.term - 1) * self.d))
raise StopIteration
def __eq__(self, o: object) -> bool:
if isinstance(o, AP):
return str(self) == str(o)
But when someone wants to convert it into a list and if it is an infinite one, I want to raise an error like:
ValueError: The list() function was called for an object of undefined length.
Same goes for sum() function as well. Are there any solutions to this?