杨辉三角
Topic source-- coding: utf-8 --
def triangles(): num = [1] while True: yield num num = [num[i] + num[i-1] for i in range(len(num))if i != 0] num.append(1) num.insert(0,1)
把for循环和里面的内容整合在一个列表生成式里面,直接生成num,就避免了需要建一个temp来保存当前num值的情况。但是需要num.insert(0,1)来为其添加第一个值。
因为如果是temp = num,那么相当于temp和num指向了同一个对象,这样如果num改变,temp会跟着改变,所以需要用temp = num[:]来复制一个当前num的副本,这样num改变就不会影响到temp的值。
大神,我把yield temp改成了yield num,结果就不对了,我理解是传回去results的是地址,内容变了,所以最后results的内容也变了,那您写的yield temp传去的应该也是temp的地址吧,如果temp内容变了,那results岂不要一起变,求大神指点下
def triangles(): num = [1] while True: temp = num[:] yield num for i in range(len(num)): if i != 0: num[i] = temp[i] + temp[i-1] num.append(1)
def triangles(): L = [1] while True: yield L L = [L[0]] + [L[i] + L[i+1] for i in range(len(L)-1)] + [L[-1]]
- 1
伞内的星空
-- coding: utf-8 --
def triangles(): num = [1] while True: temp = num[:] yield temp for i in range(len(num)): if i != 0: num[i] = temp[i] + temp[i-1] num.append(1)
还有什么能简写的地方吗?