新聞中心
python做斐波那契數(shù)列。
直接創(chuàng)建一個(gè)類然后調(diào)用下面的def函數(shù)即可
創(chuàng)新互聯(lián)是一家網(wǎng)站設(shè)計(jì)公司,集創(chuàng)意、互聯(lián)網(wǎng)應(yīng)用、軟件技術(shù)為一體的創(chuàng)意網(wǎng)站建設(shè)服務(wù)商,主營產(chǎn)品:響應(yīng)式網(wǎng)站設(shè)計(jì)、成都品牌網(wǎng)站建設(shè)、營銷型網(wǎng)站。我們專注企業(yè)品牌在網(wǎng)站中的整體樹立,網(wǎng)絡(luò)互動的體驗(yàn),以及在手機(jī)等移動端的優(yōu)質(zhì)呈現(xiàn)。網(wǎng)站制作、做網(wǎng)站、移動互聯(lián)產(chǎn)品、網(wǎng)絡(luò)運(yùn)營、VI設(shè)計(jì)、云產(chǎn)品.運(yùn)維為核心業(yè)務(wù)。為用戶提供一站式解決方案,我們深知市場的競爭激烈,認(rèn)真對待每位客戶,為客戶提供賞析悅目的作品,網(wǎng)站的價(jià)值服務(wù)。
#斐波那契數(shù)列
'''
第一位是1
第二位是1
第三位是2
公式位F(n)=f(n-1)+f(n-2)
'''
def get_Fibonacci_sequence(n):
'''輸入n,遍歷到第n位的斐波那契數(shù)列'''
a,b=0,1
if n=3:#即等于2 相當(dāng)于1,2位特殊處理
for i in range(n-1):#操作次數(shù)是n-1,去除一次第一位的操作
c=a+b
a,b,=b,c
print(b)#這里選擇先改變再輸出,可以減少1次的循環(huán)
def get_Fibonacci_Num(n):
'''輸入n,遍歷到第n位的斐波那契數(shù)列的第n位數(shù)'''
a, b = 0, 1
if n = 3: # 即等于2 相當(dāng)于1,2位特殊處理
for i in range(n - 1): # 操作次數(shù)是n-1,去除一次第一位的操作
c = a + b
a, b, = b, c
# 這里選擇先改變再輸出,可以減少1次的循環(huán)
return b
def get_Fibonacci_Num_recursion(n):
'''輸入n,遍歷到第n位的斐波那契數(shù)列的第n位數(shù),遞歸實(shí)現(xiàn)'''
if n==1 or n==2:#特別注意,這里要用邏輯或判斷,不能直接用或判斷,
return 1
else:
return get_Fibonacci_Num_recursion(n-1)+get_Fibonacci_Num_recursion(n-2)
get_Fibonacci_sequence(11)
print(get_Fibonacci_Num(11))
print(get_Fibonacci_Num_recursion(11))
pythonfabric2.0使用方法
pythonfabric2.0使用方法如下:
1、連接服務(wù)器,通過fabric.Connection方法連接服務(wù)器。
2、通過fabric安裝軟件通過一段代碼實(shí)現(xiàn)在Ubuntu上批量安裝docker,順序取走列表中的ip。fabric是一個(gè)python(2.7,3.4+)的庫,用來通過SSH遠(yuǎn)程執(zhí)行shell命令,并返回有用的python對象。fabric的典型使用方式就是,創(chuàng)建一個(gè)Python文件,該文件包含一到多個(gè)函數(shù),然后使用fab命令調(diào)用這些函數(shù)。
python生成器是怎么使用的
生成器(generator)概念
生成器不會把結(jié)果保存在一個(gè)系列中,而是保存生成器的狀態(tài),在每次進(jìn)行迭代時(shí)返回一個(gè)值,直到遇到StopIteration異常結(jié)束。
生成器語法
生成器表達(dá)式: 通列表解析語法,只不過把列表解析的[]換成()
生成器表達(dá)式能做的事情列表解析基本都能處理,只不過在需要處理的序列比較大時(shí),列表解析比較費(fèi)內(nèi)存。
Python
1
2
3
4
5
6
7
8
9
10
11
gen = (x**2 for x in range(5))
gen
generator object genexpr at 0x0000000002FB7B40
for g in gen:
... print(g, end='-')
...
0-1-4-9-16-
for x in [0,1,2,3,4,5]:
... print(x, end='-')
...
0-1-2-3-4-5-
生成器函數(shù): 在函數(shù)中如果出現(xiàn)了yield關(guān)鍵字,那么該函數(shù)就不再是普通函數(shù),而是生成器函數(shù)。
但是生成器函數(shù)可以生產(chǎn)一個(gè)無線的序列,這樣列表根本沒有辦法進(jìn)行處理。
yield 的作用就是把一個(gè)函數(shù)變成一個(gè) generator,帶有 yield 的函數(shù)不再是一個(gè)普通函數(shù),Python 解釋器會將其視為一個(gè) generator。
下面為一個(gè)可以無窮生產(chǎn)奇數(shù)的生成器函數(shù)。
Python
1
2
3
4
5
6
7
8
9
10
11
def odd():
n=1
while True:
yield n
n+=2
odd_num = odd()
count = 0
for o in odd_num:
if count =5: break
print(o)
count +=1
當(dāng)然通過手動編寫迭代器可以實(shí)現(xiàn)類似的效果,只不過生成器更加直觀易懂
Python
1
2
3
4
5
6
7
8
9
10
11
class Iter:
def __init__(self):
self.start=-1
def __iter__(self):
return self
def __next__(self):
self.start +=2
return self.start
I = Iter()
for count in range(5):
print(next(I))
題外話: 生成器是包含有__iter()和next__()方法的,所以可以直接使用for來迭代,而沒有包含StopIteration的自編Iter來只能通過手動循環(huán)來迭代。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from collections import Iterable
from collections import Iterator
isinstance(odd_num, Iterable)
True
isinstance(odd_num, Iterator)
True
iter(odd_num) is odd_num
True
help(odd_num)
Help on generator object:
odd = class generator(object)
| Methods defined here:
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
......
看到上面的結(jié)果,現(xiàn)在你可以很有信心的按照Iterator的方式進(jìn)行循環(huán)了吧!
在 for 循環(huán)執(zhí)行時(shí),每次循環(huán)都會執(zhí)行 fab 函數(shù)內(nèi)部的代碼,執(zhí)行到 yield b 時(shí),fab 函數(shù)就返回一個(gè)迭代值,下次迭代時(shí),代碼從 yield b 的下一條語句繼續(xù)執(zhí)行,而函數(shù)的本地變量看起來和上次中斷執(zhí)行前是完全一樣的,于是函數(shù)繼續(xù)執(zhí)行,直到再次遇到 yield??雌饋砭秃孟褚粋€(gè)函數(shù)在正常執(zhí)行的過程中被 yield 中斷了數(shù)次,每次中斷都會通過 yield 返回當(dāng)前的迭代值。
yield 與 return
在一個(gè)生成器中,如果沒有return,則默認(rèn)執(zhí)行到函數(shù)完畢時(shí)返回StopIteration;
Python
1
2
3
4
5
6
7
8
9
10
11
def g1():
... yield 1
...
g=g1()
next(g) #第一次調(diào)用next(g)時(shí),會在執(zhí)行完yield語句后掛起,所以此時(shí)程序并沒有執(zhí)行結(jié)束。
1
next(g) #程序試圖從yield語句的下一條語句開始執(zhí)行,發(fā)現(xiàn)已經(jīng)到了結(jié)尾,所以拋出StopIteration異常。
Traceback (most recent call last):
File "stdin", line 1, in module
StopIteration
如果遇到return,如果在執(zhí)行過程中 return,則直接拋出 StopIteration 終止迭代。
Python
1
2
3
4
5
6
7
8
9
10
11
12
def g2():
... yield 'a'
... return
... yield 'b'
...
g=g2()
next(g) #程序停留在執(zhí)行完yield 'a'語句后的位置。
'a'
next(g) #程序發(fā)現(xiàn)下一條語句是return,所以拋出StopIteration異常,這樣yield 'b'語句永遠(yuǎn)也不會執(zhí)行。
Traceback (most recent call last):
File "stdin", line 1, in module
StopIteration
如果在return后返回一個(gè)值,那么這個(gè)值為StopIteration異常的說明,不是程序的返回值。
生成器沒有辦法使用return來返回值。
Python
1
2
3
4
5
6
7
8
9
10
11
def g3():
... yield 'hello'
... return 'world'
...
g=g3()
next(g)
'hello'
next(g)
Traceback (most recent call last):
File "stdin", line 1, in module
StopIteration: world
生成器支持的方法
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
help(odd_num)
Help on generator object:
odd = class generator(object)
| Methods defined here:
......
| close(...)
| close() - raise GeneratorExit inside generator.
|
| send(...)
| send(arg) - send 'arg' into generator,
| return next yielded value or raise StopIteration.
|
| throw(...)
| throw(typ[,val[,tb]]) - raise exception in generator,
| return next yielded value or raise StopIteration.
......
close()
手動關(guān)閉生成器函數(shù),后面的調(diào)用會直接返回StopIteration異常。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
def g4():
... yield 1
... yield 2
... yield 3
...
g=g4()
next(g)
1
g.close()
next(g) #關(guān)閉后,yield 2和yield 3語句將不再起作用
Traceback (most recent call last):
File "stdin", line 1, in module
StopIteration
send()
生成器函數(shù)最大的特點(diǎn)是可以接受外部傳入的一個(gè)變量,并根據(jù)變量內(nèi)容計(jì)算結(jié)果后返回。
這是生成器函數(shù)最難理解的地方,也是最重要的地方,實(shí)現(xiàn)后面我會講到的協(xié)程就全靠它了。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
def gen():
value=0
while True:
receive=yield value
if receive=='e':
break
value = 'got: %s' % receive
g=gen()
print(g.send(None))
print(g.send('aaa'))
print(g.send(3))
print(g.send('e'))
執(zhí)行流程:
通過g.send(None)或者next(g)可以啟動生成器函數(shù),并執(zhí)行到第一個(gè)yield語句結(jié)束的位置。此時(shí),執(zhí)行完了yield語句,但是沒有給receive賦值。yield value會輸出初始值0注意:在啟動生成器函數(shù)時(shí)只能send(None),如果試圖輸入其它的值都會得到錯(cuò)誤提示信息。
通過g.send(‘a(chǎn)aa’),會傳入aaa,并賦值給receive,然后計(jì)算出value的值,并回到while頭部,執(zhí)行yield value語句有停止。此時(shí)yield value會輸出”got: aaa”,然后掛起。
通過g.send(3),會重復(fù)第2步,最后輸出結(jié)果為”got: 3″
當(dāng)我們g.send(‘e’)時(shí),程序會執(zhí)行break然后推出循環(huán),最后整個(gè)函數(shù)執(zhí)行完畢,所以會得到StopIteration異常。
最后的執(zhí)行結(jié)果如下:
Python
1
2
3
4
5
6
7
got: aaa
got: 3
Traceback (most recent call last):
File "h.py", line 14, in module
print(g.send('e'))
StopIteration
throw()
用來向生成器函數(shù)送入一個(gè)異常,可以結(jié)束系統(tǒng)定義的異常,或者自定義的異常。
throw()后直接跑出異常并結(jié)束程序,或者消耗掉一個(gè)yield,或者在沒有下一個(gè)yield的時(shí)候直接進(jìn)行到程序的結(jié)尾。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def gen():
while True:
try:
yield 'normal value'
yield 'normal value 2'
print('here')
except ValueError:
print('we got ValueError here')
except TypeError:
break
g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))
print(g.throw(TypeError))
輸出結(jié)果為:
Python
1
2
3
4
5
6
7
8
normal value
we got ValueError here
normal value
normal value 2
Traceback (most recent call last):
File "h.py", line 15, in module
print(g.throw(TypeError))
StopIteration
解釋:
print(next(g)):會輸出normal value,并停留在yield ‘normal value 2’之前。
由于執(zhí)行了g.throw(ValueError),所以會跳過所有后續(xù)的try語句,也就是說yield ‘normal value 2’不會被執(zhí)行,然后進(jìn)入到except語句,打印出we got ValueError here。然后再次進(jìn)入到while語句部分,消耗一個(gè)yield,所以會輸出normal value。
print(next(g)),會執(zhí)行yield ‘normal value 2’語句,并停留在執(zhí)行完該語句后的位置。
g.throw(TypeError):會跳出try語句,從而print(‘here’)不會被執(zhí)行,然后執(zhí)行break語句,跳出while循環(huán),然后到達(dá)程序結(jié)尾,所以跑出StopIteration異常。
下面給出一個(gè)綜合例子,用來把一個(gè)多維列表展開,或者說扁平化多維列表)
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def flatten(nested):
try:
#如果是字符串,那么手動拋出TypeError。
if isinstance(nested, str):
raise TypeError
for sublist in nested:
#yield flatten(sublist)
for element in flatten(sublist):
#yield element
print('got:', element)
except TypeError:
#print('here')
yield nested
L=['aaadf',[1,2,3],2,4,[5,[6,[8,[9]],'ddf'],7]]
for num in flatten(L):
print(num)
如果理解起來有點(diǎn)困難,那么把print語句的注釋打開在進(jìn)行查看就比較明了了。
總結(jié)
按照鴨子模型理論,生成器就是一種迭代器,可以使用for進(jìn)行迭代。
第一次執(zhí)行next(generator)時(shí),會執(zhí)行完yield語句后程序進(jìn)行掛起,所有的參數(shù)和狀態(tài)會進(jìn)行保存。再一次執(zhí)行next(generator)時(shí),會從掛起的狀態(tài)開始往后執(zhí)行。在遇到程序的結(jié)尾或者遇到StopIteration時(shí),循環(huán)結(jié)束。
可以通過generator.send(arg)來傳入?yún)?shù),這是協(xié)程模型。
可以通過generator.throw(exception)來傳入一個(gè)異常。throw語句會消耗掉一個(gè)yield??梢酝ㄟ^generator.close()來手動關(guān)閉生成器。
next()等價(jià)于send(None)
python楊輝三角形原理
triangles里用到了yield,yield 的作用就是把一個(gè)函數(shù)變成一個(gè) generator,帶有 yield 的函數(shù)不再是一個(gè)普通函數(shù),Python 解釋器會將其視為一個(gè) generator,調(diào)用 triangles(5) 不會執(zhí)行 triangles函數(shù),而是返回一個(gè) iterable 對象!在 for 循環(huán)執(zhí)行時(shí),每次循環(huán)都會執(zhí)行 fab 函數(shù)內(nèi)部的代碼,執(zhí)行到 yield L 時(shí),triangles函數(shù)就返回一個(gè)迭代值,下次迭代時(shí),代碼從 yield L?的下一條語句繼續(xù)執(zhí)行,而函數(shù)的本地變量看起來和上次中斷執(zhí)行前是完全一樣的,于是函數(shù)繼續(xù)執(zhí)行,直到再次遇到 yield。
1?那個(gè)2去哪了
你看else語句?L1 = [1,1]每次L都是基于這個(gè)L1生成的 比如L=[1,2,1] 那么下一個(gè)L1就是[1,3,3,1],下一句L = L1 所以每次都是新的L1生成
2?畫紅圈的地方應(yīng)該是和L1.insert(i,L[i-1+i])意思一樣
不一樣,插入的值是兩個(gè)數(shù)的和
def?triangles(max):
L?=?[1]
n?=?0
while(nmax):
n?=?n+1
if(n?==?2):
L=[1,1]
yield?L
else:
i?=?1
L1?=?[1,1]
while(i=n-2):
L1.insert(i,L[i-1]+L[i])
i=i+1
L?=?L1
yield?L
for?n?in?triangles(5):
print?n
網(wǎng)頁標(biāo)題:fab函數(shù)Python python fact函數(shù)
本文路徑:http://fisionsoft.com.cn/article/doeipop.html