标签:else 列表 学编程 解法 应该 nbsp 思考 com sum
1 # 传统的杨辉三角形实现 2 def pascal(row): 3 result_list = [0] * (row * 2 + 1) 4 5 for row_loc in range(row): 6 base_loc = row - row_loc - 1 7 if row_loc == 0: 8 result_list[base_loc] = 1 9 else: 10 result_list[base_loc] = result_list[base_loc + 1] 11 for line_loc in range(row_loc): 12 now_loc = base_loc + (line_loc + 1) * 2 13 result_list[now_loc] = result_list[now_loc - 1] + result_list[now_loc + 1] 14 result_list[now_loc - 1] = 0 15 16 print str(result_list) 17 .replace("]", ",").replace(" 0,", " ").replace(",", "").replace("[0", " ").replace("[", " ") 18 19 pascal(15)
1 # 利用python列表迭代的实现 2 def printLine(lineList,row): 3 lineList = [str(tmpNum) for tmpNum in lineList] 4 print("%s%s" % (" " * (row - len(lineList)), " ".join(lineList))) 5 6 def pascal(row): 7 for i in range(row): 8 if i < 2: 9 yhList = [1] * (i + 1) 10 else: 11 yhList[1:-1] = [(tmpNum + yhList[j]) for j, tmpNum in enumerate(yhList[1:])] 12 printLine(yhList,row) 13 14 pascal(10)
1 # 基于函数式编程思路的实现 2 def row(x): 3 return ‘ ‘.join(map(str, reduce(lambda x, y: map( sum, zip([0] + x, x + [0]) ), range(x), [1] ))) 4 5 def pascal(x): 6 return ‘\n‘.join(row(i).center(len(row(x - 1))) for i in range(x)) 7 8 print pascal(10)
标签:else 列表 学编程 解法 应该 nbsp 思考 com sum
原文地址:https://www.cnblogs.com/kevins-yuan/p/9990449.html