斐波拉契数列:
In [31]: def func(times): ...: alist = [0,1] ...: sum = 0 ...: for i in range(times): ...: ...: sum = alist[-2] + alist[-1] ...: alist.append(sum) ...: sum = 0 ...: return alist ...: In [32]: In [32]: print(func(5)) [0, 1, 1, 2, 3, 5, 8] In [33]: print(func(10)) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
有趣的面试题:
在没有第三个数的情况下,实现两个数值交换,a = 10,b= 9,交换后a = 9 ,b = 10
In [34]: a = 10 In [35]: b = 9 In [36]: a = a + b In [37]: b = a - b In [38]: a = a - b In [39]: a Out[39]: 9 In [40]: b Out[40]: 10
################生成器######################
[root@master gaoji]# cat test.py #!/usr/local/bin/python3 # -*- coding:utf-8 -*- def creatNum(): print('----start---') a,b = 0,1 for i in range(5): print('---1---') yield b print('---2---') a,b = b,a + b print('---3---') print('----stop----')
结果:
In [1]: import test In [2]: a = test.creatNum() In [3]: next(a) ----start--- ---1--- Out[3]: 1 In [4]: next(a) ---2--- ---3--- ---1--- Out[4]: 1 In [5]: next(a) ---2--- ---3--- ---1--- Out[5]: 2 In [6]: next(a) ---2--- ---3--- ---1--- Out[6]: 3
################生成器之传送数据send################
[root@master gaoji]# vim test1.py 1 #!/usr/local/bin/python3 2 # -*- coding:utf-8 -*- 3 4 5 def test(): #第一次执行a.__next__() ,i=0,走到yield i,有yield返回数值0,此时停止不动,再执行a.__next__(),由yield 地方继续,此时并不是把yield i 的返回值 6 i = 0 赋值给temp,此时temp的值为None,再继续i+=1,此时i=1,符合while条件,继续下面的语句,此时有yield i,返回yield 1的值,输出1,又停止不动,等待a.__next__()的调用执行,一直循环 7 while i < 5: 8 temp = yield i 9 print(temp) 10 i+=1
运行结果:
[root@master gaoji]# python3 Python 3.5.4 (default, Oct 7 2017, 12:39:20) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from test1 import * >>> a = test() >>> a <generator object test at 0x7f35bca38258> >>> a.__next__() 0 >>> a.__next__() None 1 >>> a.__next__() None 2
>>> a.send("haha") ###如果使用send,则是把值传给变量
haha
3
>>> a.send("hello")
hello
4
###########使用案例场景##############
多任务案例,也就是多个任务同时进行