Fib Class
# Fred Baptiste Python Deep Dive (Part 2 - Iterators and Generators)
from functools import lru_cache
class Fib:
def __init__(self, n):
self._n = n
def __len__(self):
return self._n
def __getitem__(self, s):
if isinstance(s, int):
if s < 0:
s = self._n + s
if 0 < s > self._n - 1:
raise IndexError
return self._fib(s)
else:
# s = 'python'
# s = slice(0, 6, 2)
# print(f'[{s.start}:{s.stop}:{s.step}]')
# print(s.indices(6))
idx = s.indices(self._n)
return [self._fib(n) for n in range(idx[0], idx[1], idx[2])]
# https://stackabuse.com/pythons-classmethod-and-staticmethod-explained/
@staticmethod
@lru_cache(2**10)
def _fib(n):
if n < 2:
return 1
else:
return Fib._fib(n-1) + Fib._fib(n-2)
f = Fib(10)
print(f[0:5])
print(f[5::-1])
print(f[5])
print(list(f))
print(f[0:10])
print(f[::-1])
print(len(f))