Python实现斐波那契数列
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=‘ ‘)
相关推荐
bizercsdn 2020-03-27
JakobHu 2020-01-03
llwang0 2019-12-28
GhostLWB 2019-12-14
qitong 2019-11-04
风吹夏天 2019-11-03
seekerhit 2019-10-20
Broadview 2019-06-27
风和日丽 2019-06-27
taiyangshenniao 2019-06-27
动态规划有时被称为递归的相反的技术。动态规划方案通常使用一个数组来建立一张表,用于存放被分解成众多子问题的解。当算法执行完毕,最终的解法将会在这个表中找到。今天我们先从我们最熟的斐波那契数列数列开始。
WindChaser 2019-06-21
hujun0 2013-03-19
HappyRocking 2019-05-16
HMHYY 2019-03-19
HeyShHeyou 2018-01-16
tingke 2015-08-09
天恒永恒 2017-01-12
iamlazyphper 2017-12-11