使用python生成杨辉三角形的示例代码
杨辉三角杨辉 定义如下:
1 / \ 1 1 / \ / \ 1 2 1 / \ / \ / \ 1 3 3 1 / \ / \ / \ / \ 1 4 6 4 1 / \ / \ / \ / \ / \ 1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
def triangles(): L = [1] while True: yield L M=L[:]#复制一个list,这样才不会影响到原有的list。不然results里的每个列表的末尾会为0. M.append(0) L = [M[i-1]+M[i] for i in range(len(M))] n =0 results = [] for t in triangles(): print(t) results.append(t) print(results) n = n +1 if n == 10: break
ps:如何实现心
def printlove(start,length,midnumber=0,flag=31): for i in range(31): if i<start or i>start+length-1 and i<15-(midnumber-1)/2 or i>15+(midnumber-1)/2 and i<31-start-length or i> 30-start or i==flag: print " ", else: print "*", print "" for i in range(16): if i ==0: printlove(4,3) elif i==1: printlove(1,9) elif i>=2 and i<=5: printlove(0,i+10) elif i==6: printlove(1,7,7,15) elif i>=7 and i<=8: printlove(i-5,6,5-(i-7)*2) elif i==9: printlove(5,6,1) elif i==10: printlove(8,6,1) elif i==15: printlove(15,1,1) else: printlove(i-1,16-i,1)
实现的效果如下:
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16