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)