测试用方法如下
# -*- coding:utf-8 -*- #杨辉三角 def triangles(max): L=[] while len(L)<max: #继续循环 last=1 #if len(L)>1: #因为下面是从1开始的所以当len(L)<=1时可以忽略循环 for n in range(1,len(L)): #temp=L[n] #可以下行同时代替 L[n],last=L[n]+last,L[n] #last=temp #可以下行同时代替 L.append(1) print(L) print('finish')
然后改成g的方法就是将while len(L)<max: 改成 while True: 将print(L)改成yield L
测试结果:
n=0 for t in triangles(): print(t) n=n+1 if n==10: break
[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
Sign in to make a reply
Sevenup_文烁_愿做这种人
测试用方法如下
然后改成g的方法就是将while len(L)<max: 改成 while True: 将print(L)改成yield L
测试结果:
[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]