巧妙实现杨辉三角代码 def triangles(): N=[1] #初始化为[1],杨辉三角的每一行为一个list while True: yield N #yield 实现记录功能,没有下一个next将跳出循环, S=N[:] #将list N赋给S,通过S计算每一行 S.append(0) #将list添加0,作为最后一个元素,长度增加1 N=[S[i-1]+S[i] for i in range(len(S))] #通过S来计算得出N n = 0 results = [] for t i
1 #! usr/bin/env python3 #-*- coding :utf-8 -*- print('杨辉三角的generator') def triangles(): N=[1] while True : yield N N.append(0) N = [N[i-1]+N[i] for i in range(len(N)) ] triangles = triangles() for j in range(10): print ( next(triangles)) 敲打了如上的代码.在命
使用python列表,展示杨辉三角 # !/usr/bin/env python # -*- coding:utf-8 -*- # Author:Hiuhung Wan yanghui = [] for i in range(1, 11): if i == 1: list0 = [1] elif i == 2: list0 = [1, 1] else: list0 = [1] * i for j in range(1, i - 1): list0[j] = yanghui[-1][j - 1]
def yanghui(lines): currentlst,lastlst,n=[],[],1 if lines<1: return while n<=lines: lastlst=currentlst currentlst=[] for i in range(n): if(i==0): currentlst.insert(0,1) elif(i==n-1): currentlst.insert(i,1) else: currentlst.insert(i,lastlst[i]+lastls