Advertisement
Guest User

Fibonacci class problem

a guest
Oct 22nd, 2019
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. """
  2. Here you will find my implementation for the following proposed problem:
  3.  
  4. # 1. Create a class with a method that returns a generator for a fibonacci sequence, given a max number of iterations.
  5.  
  6. # 2. Create a decorator that constraints the max number of iterations to 10 for the implemented method. In case of a higher number, throw an exception.
  7.  
  8. # 3. Make the implemented class iterable over the generator, with max parameter set to 10.
  9. """
  10.  
  11.  
  12. def limit_iter(func):
  13.     """Limit the number of iterations to 10."""
  14.    
  15.     def wrapper(cls, max_iter):
  16.         if max_iter > 10:
  17.             raise ValueError('This method can have a maximum of 10 iterations.')
  18.         return func(cls, max_iter)
  19.     return wrapper
  20.        
  21.  
  22. class Fibo(object):
  23.     cur_idx = 0
  24.     fibo_list = []
  25.     fibo_generator = None
  26.    
  27.     def __init__(self):
  28.         self.cur_idx = 0
  29.         self.fibo_list = []
  30.         self.fibo_generator = None
  31.    
  32.     def __iter__(self):
  33.         self.cur_idx = 0
  34.         self.fibo_generator = self.generate(10)
  35.         return self
  36.    
  37.     def __next__(self):
  38.         return next(self.fibo_generator)
  39.    
  40.     def next_term(self):
  41.         """Return next Fibonacci sequence item.
  42.        
  43.        By default, expects there will be enough terms, as this is what will
  44.        happen most of the time (avoids several checks).
  45.        """
  46.         try:
  47.             term = self.fibo_list[-1] + self.fibo_list[-2]
  48.         except:
  49.             term = len(self.fibo_list) # 0 if no items yet, 1 otherwise
  50.         finally:
  51.             return term
  52.    
  53.     @limit_iter
  54.     def generate(self, max_iter):
  55.         """Return a generator for Fibonacci sequence with a maximum of
  56.        `max_iter` iterations.
  57.        """
  58.        
  59.         while len(self.fibo_list) < max_iter:
  60.             term = self.next_term()
  61.             self.fibo_list.append(term)
  62.             yield term
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement