Kwong 2019-12-02
1、最普通的写法
def fibonaci(num): a = 0 b = 1 print(a, end=" ") for _ in range(num): c = a + b a = b b = c print(a, end=" ") fibonaci(10)
2、Python风格的写法
def fibonaci(num): a = 0 b = 1 print(a, end=" ") for _ in range(num): a, b = b, a+b print(a, end=" ") fibonaci(10)
3、Python的迭代器实现
class Fibonacci: def __init__(self, max_num): self.max_num = max_num self.current_num = 0 self.first_num = 0 self.second_num = 1 def __iter__(self): return self def __next__(self): if self.current_num < self.max_num: result = self.first_num self.first_num, self.second_num = self.second_num, self.first_num + self.second_num self.current_num += 1 return result else: raise StopIteration # 创建斐波那契额对象 f = Fibonacci(10) for i in f: print(i, end=‘ ‘)
动态规划有时被称为递归的相反的技术。动态规划方案通常使用一个数组来建立一张表,用于存放被分解成众多子问题的解。当算法执行完毕,最终的解法将会在这个表中找到。今天我们先从我们最熟的斐波那契数列数列开始。