Advertisement
Rementai

Iterator

Mar 30th, 2023
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. class MyRangeIterator:
  2.     def __init__(self, *args):
  3.         self.number_of_args = len(args)
  4.         if self.number_of_args == 1:
  5.             self.start, self.stop, self.step = 0.0, args[0], 1.0
  6.         elif self.number_of_args == 2:
  7.             self.start, self.stop, self.step = args[0], args[1], 1.0
  8.         elif self.number_of_args == 3:
  9.             self.start, self.stop, self.step = args[0], args[1], args[2]
  10.         else:
  11.             raise ValueError("Function needs 1 to 3 arguments.")
  12.  
  13.         if self.step == 0:
  14.             raise ValueError("Step argument cannot be 0")
  15.  
  16.         self.current = self.start
  17.  
  18.     def __iter__(self):
  19.         return self
  20.  
  21.     def __next__(self):
  22.         if (self.step > 0 and self.current >= self.stop) or (self.step < 0 and self.current <= self.stop):
  23.             raise StopIteration
  24.         else:
  25.             result = self.current
  26.             self.current += self.step
  27.             return result
  28.  
  29. def main():
  30.     try:
  31.         my_range_iterator = MyRangeIterator(1.1, 2.2, 0.5)
  32.         for val in my_range_iterator:
  33.             print(val, end=" ")
  34.         print()
  35.  
  36.         my_range_iterator = MyRangeIterator(1.1, 2.1, 0.5)
  37.         for val in my_range_iterator:
  38.             print(val, end=" ")
  39.         print()
  40.  
  41.         my_range_iterator = MyRangeIterator(1.1, 2.2)
  42.         for val in my_range_iterator:
  43.             print(val, end=" ")
  44.         print()
  45.  
  46.         my_range_iterator = MyRangeIterator(2.2)
  47.         for val in my_range_iterator:
  48.             print(val, end=" ")
  49.         print()
  50.  
  51.         my_range_iterator = MyRangeIterator(1.9, 0.9, -0.5)
  52.         for val in my_range_iterator:
  53.             print(val, end=" ")
  54.         print()
  55.  
  56.         my_range_iterator = MyRangeIterator()
  57.         for val in my_range_iterator:
  58.             print(val, end=" ")
  59.         print()
  60.  
  61.     except ValueError as e:
  62.         print("Error:", e)
  63.  
  64. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement