Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Here you will find my implementation for the following proposed problem:
- # 1. Create a class with a method that returns a generator for a fibonacci sequence, given a max number of iterations.
- # 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.
- # 3. Make the implemented class iterable over the generator, with max parameter set to 10.
- """
- def limit_iter(func):
- """Limit the number of iterations to 10."""
- def wrapper(cls, max_iter):
- if max_iter > 10:
- raise ValueError('This method can have a maximum of 10 iterations.')
- return func(cls, max_iter)
- return wrapper
- class Fibo(object):
- cur_idx = 0
- fibo_list = []
- fibo_generator = None
- def __init__(self):
- self.cur_idx = 0
- self.fibo_list = []
- self.fibo_generator = None
- def __iter__(self):
- self.cur_idx = 0
- self.fibo_generator = self.generate(10)
- return self
- def __next__(self):
- return next(self.fibo_generator)
- def next_term(self):
- """Return next Fibonacci sequence item.
- By default, expects there will be enough terms, as this is what will
- happen most of the time (avoids several checks).
- """
- try:
- term = self.fibo_list[-1] + self.fibo_list[-2]
- except:
- term = len(self.fibo_list) # 0 if no items yet, 1 otherwise
- finally:
- return term
- @limit_iter
- def generate(self, max_iter):
- """Return a generator for Fibonacci sequence with a maximum of
- `max_iter` iterations.
- """
- while len(self.fibo_list) < max_iter:
- term = self.next_term()
- self.fibo_list.append(term)
- yield term
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement