import math import decimal from timeit import default_timer as timer from typing importCallable, OrderedDict, Tuple, List from functools import lru_cache
classFibonacci:
num: int times: OrderedDict memory: List[int] MAXSIZE: int def_get_time(self, fn: Callable) -> Tuple[float, int]: start = timer() result = fn() end = timer() return end - start, result
defprint_results(self): print("-------------------------------------") print("n = {}".format(self.num)) for k, v in self.times.items(): print("{0}: \t时间为\t{1}微秒,\t结果为{2}。".format(k, round(decimal.Decimal(v[0] * math.pow(10, 6)), 1), v[1]))
def_fib_1(self, n: int) -> int: if n == 0: return0 if n == 1: return1 return self._fib_1(n-1) + self._fib_1(n-2)
@lru_cache(maxsize=20) def_fib_2(self, n: int) -> int: if n == 0: return0 if n == 1: return1 return self._fib_2(n-1) + self._fib_2(n-2)
def_fib_3(self, n: int) -> int: pre = 0 next = 1 result = 0 if n == 0: return pre if n == 1: returnnext while (n := n - 1) >= 1: # 注意n的值 result = pre + next pre = next next = result return result
def_fib_5(self, n: int) -> int: if n == 0or n == 1: return n em = [[1, 1], [1, 0]] return self._matrixPow(em, n + 1)[1][1]
def_fib_6(self, n: int) -> int: if n == 0or n == 1: return n em = [[0, 1], [0, 0]] # 系数 rhm = [[0, 1], [1, 1]]
return self._matrixMultiply(em, self._matrixPow(rhm, n - 1))[0][1]
def_matrixMultiply(self, x: List[List[int]], y: List[List[int]]) -> List[List[int]]: # https://stackoverflow.com/a/10508239 # zip_rhm = list(zip(*rhm)) # return [[sum(map(lambda x, y: x * y, row_lhm, col_rhm)) for col_rhm in zip_rhm] for row_lhm in lhm] return [[x[0][0] * y[0][0] + x[0][1] * y[0][1], x[0][0] * y[0][1] + x[0][1] * y[1][1]], [x[1][0] * y[0][0] + x[1][1] * y[0][1], x[1][0] * y[1][0] + x[1][1] * y[1][1]]]
def_matrixPow(self, m: List[List[int]], n: int) -> List[List[int]]: r = m res = [[1, 0], [0, 1]] # while n != 0: # if n & 1 == 1: # res = self._matrixMultiply(res, r) # r = self._matrixMultiply(r, r) # n >>= 1 n <<= 1 while (n := n >> 1) != 0: if n & 1 == 1: res = self._matrixMultiply(res, r) r = self._matrixMultiply(r, r) return res
def_fib_7(self, n: int) -> int: if n == 0or n == 1: return n if n == 2: return1 self.memory = [-1for x inrange(n+1)] self.memory[0] = 0 self.memory[1] = 1 self.memory[2] = 1 for i inrange(3, n + 1): self.memory[i] = self.memory[i-1] + self.memory[i-2] return self.memory[n]
def_fib_8(self, n: int) -> int: if n == 0or n == 1: return n if n == 2: return1 self.memory = [0, 1, 1] for i inrange(3, n+1): self.memory[i%3] = self.memory[(i-2)%3] + self.memory[(i-1)%3] return self.memory[n%3]
def_memory_reset(self): self.memory = [-1for i inrange(self.num + 1)]