python杨辉三角形的实现

def triangles():
    L = [1]
    while True:
        yield L
        L = [sum(i) for i in zip([0] + L, L + [0])]

def abs():
    n = 0
    for t in triangles():
        print(t)
        n = n + 1
        if n == 10:
         break

print(abs())

在网上查的其他的实现,写的也很好,就是记着导包:
##实现一:
def pascal(row):
    result_list = [0] * (row * 2 + 1)
    for row_loc in range(row):
        base_loc = row - row_loc - 1
        if row_loc == 0:
            result_list[base_loc] = 1
        else:
            result_list[base_loc] = result_list[base_loc + 1]
            for line_loc in range(row_loc):
                now_loc = base_loc + (line_loc + 1) * 2
                result_list[now_loc] = result_list[now_loc - 1] + result_list[now_loc + 1]
                result_list[now_loc - 1] = 0
        print(str(result_list).replace("]", ",").replace(" 0,", "  ").replace(",", "").replace("[0", "  ").replace("[", " "))

pascal(15)
# 实现二:
def printLine(lineList,row):
    lineList = [str(tmpNum) for tmpNum in lineList]
    print("%s%s" % (" " * (row - len(lineList)), " ".join(lineList)))

def pascal(row):
    for i in range(row):
        if i < 2:
            yhList = [1] * (i + 1)
        else:
            yhList[1:-1] = [(tmpNum + yhList[j])  for j, tmpNum in enumerate(yhList[1:])]
        printLine(yhList,row)

pascal(10)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值