Python实现fibnacci
2015-07-31 17:32
711 查看
2014-10-29
今天面试python实习,其中一道题是实现fibnacci。分别写出三种方法
方法1:if else模仿三目运算符
f=lambda x:1 if x<2 else f(x-1)+f(x-2)
方法2:and or 模仿三目运算符
f1=lambda x: x<2 and 1 or (f1(x-1) +f1(x-2))
方法3:使用genarator
def f2(x): a=1 b=1 n=1 while n<x: yield a n=n+1 a,b=a+b,a
测试:
for i in range(10): print f(i), f1(i)
for n in f2(10): print n
结果: 1 1 1 1 2 2 3 3 5 5 8 8 13 13 21 21 34 34 55 55 1 2 3 5 8 13 21 34 55
今天面试python实习,其中一道题是实现fibnacci。分别写出三种方法
方法1:if else模仿三目运算符
f=lambda x:1 if x<2 else f(x-1)+f(x-2)
方法2:and or 模仿三目运算符
f1=lambda x: x<2 and 1 or (f1(x-1) +f1(x-2))
方法3:使用genarator
def f2(x): a=1 b=1 n=1 while n<x: yield a n=n+1 a,b=a+b,a
测试:
for i in range(10): print f(i), f1(i)
for n in f2(10): print n
结果: 1 1 1 1 2 2 3 3 5 5 8 8 13 13 21 21 34 34 55 55 1 2 3 5 8 13 21 34 55
相关文章推荐
- Python初步
- Python调用windows下DLL详解 - ctypes库的使用
- python 函数式编程
- Python GUI编程各种实现的对比
- python Iterable和Iterator
- Python中的局部变量和全局变量
- python range()函数
- python实现爬图,不要再爬妹子图了,太没品
- python的range()函数用法
- spark 集群运行python作业
- python 生成器
- python初学小结4
- python初学小结2
- python初学小结3
- Python下用Google Map查询地址的经纬度
- python初学小结1
- python字符串操作
- openCV—Python(8)—— 图像直方图及其直方图均衡化
- Python学习资料汇总
- webQQ 中hash值的计算 python实现 2015年7月