学习笔记(1)
python生成器实现杨辉三角
def yanghui():
l=[1]
while True:
yield l
l=[l[i]+l[i+1] for i in range(len(l)-1)] ##当range(0)时,l=[]
l.append(1)
l.insert(0,1)
L=[]
n=0
for i in yanghui():
L.append(i)
n=n+1
if n==10:
break
print(L)
python生成器实现斐波那契数列
def feb(n):
a,b,c = 0,0,1
while a<n:
yield c
b,c=c,b+c
a=a+1
febnumber=[]
for i in feb(10):
febnumber.append(i)
print(febnumber)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
斐波那契数列2
def feb2():
b,c = 0,1
while True:
yield c
b,c=c,b+c
febnumber=[]
n=0
for x in feb2():
febnumber.append(x)
n=n+1
if n==10:
break
print(febnumber)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]