题目
第一次尝试:
def triangles():
while True:
list=[0,1,0]
m=1
while m<5:
m+=1
g=[]
for i in range(m-1):
x=list[i]+list[i+1]
g.append(x)
yield g
list = g
list.insert(0, 0)
list.append(0)
a=[]
for i in triangles():
print(i)
a.append(i)
print(a)
出现一下未知错误:
于是向网友咨询.把append(i)换成a.append(list(i))
结果属实可行,但是和上述题中的要求有所不服,经过和网友的讨论,得出不能将list=g,这样会导致list实际指向的是g,致使g和list实际上是一个对象,所以在下面对list的修改也引起了对g的变化,致使在加入列表的时候变成了[0,1,0]的现象(如有大佬有不同想法,欢迎指教!qq:226998414)
搞完这里继续探索题目,决定去掉list,在原列表上操作得出最终代码:
def triangles():
g=[1]
while True:
yield g
g = [g[x] + g[x + 1] for x in range(len(g) - 1)]
g.append(1)
g.insert(0,1)
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
if results == [
[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]
]:
print('测试通过!')
else:
print('测试失败!')
成功运行!
[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]
测试通过!
其中对yield用法可参考这个讲的挺容易懂的
转载:https://blog.csdn.net/qq_45227990/article/details/104642549
查看评论