1. 普通实现
理解本实现方式,需要具备的 Python 进阶语法请参见:
from typing import List
class Fibonacci:
def __init__(self, n: int):
self.n = n
self._memo = [0] * self.n
if self.n == 0 or self.n == 1:
self._memo[self.n] = 1
self._memo[0] = self._memo[1] = 1
for i in range(2, self.n):
self._memo[i] = self._memo[i - 1] + self._memo[i - 2]
@property
def last(self):
return self._memo[-1]
@property
def sequence(self) -> List[int]:
return list(self._memo)
def main():
fib = Fibonacci(6)
print(fib.sequence)
print(fib.last)
if __name__ == '__main__':
main()
2. 高效实现
理解本实现方式,需要具备的 Python 进阶语法请参见:
class EfficientFibonacci:
def __init__(self, n: int):
self.n = n
self._prev = 1
self._cur = 1
self._index = 1
def __iter__(self):
for i in range(0, self.n):
yield next(self)
def __next__(self):
if self._index <= self.n:
if self._index == 1 or self._index == 2:
self._index += 1
return 1
self._cur, self._prev = self._cur + self._prev, self._cur
element = self._cur
self._index += 1
return element
else:
raise StopIteration
def main():
efficient_fib = list(EfficientFibonacci(6))
print(efficient_fib)
print(efficient_fib[-1])
if __name__ == '__main__':
main()
|