zoukankan      html  css  js  c++  java
  • Python实现杨辉三角

    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1],
    [1, 4, 6, 4, 1],
    [1, 5, 10, 10, 5, 1],
    [1, 6, 15, 20, 15, 6, 1],
    [1, 7, 21, 35, 35, 21, 7, 1],
    [1, 8, 28, 56, 70, 56, 28, 8, 1],
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
    
    先说思路:我们把每一次层看作一个list, 通过一个for循环,通过迭代,
    每次生成一个list,而生成器就在每一行生成list中起作用,我们先定义
    一个函数,作用是生成每一行的list对于每一行,list 的第一个元素和最
    后一个元素是不变的。如果用L = [] 表示的话, L[0], L[n],是 不变的
    
    def yhTriangle(n):
        l, index = [1], 0
        while index < n:
            yield l
            l = [1] + [l[i] + l[i + 1] for i in range(len(l) - 1)] + [1]
            index += 1
    
    for i in yhTriangle(10):
        print(i)
    
    结果:
    [1]
    [1, 1]
    [1, 2, 1]
    [1, 3, 3, 1]
    [1, 4, 6, 4, 1]
    [1, 5, 10, 10, 5, 1]
    [1, 6, 15, 20, 15, 6, 1]
    [1, 7, 21, 35, 35, 21, 7, 1]
    [1, 8, 28, 56, 70, 56, 28, 8, 1]
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
  • 相关阅读:
    linux日常。
    tp5中的config类和config助手函数
    TP5隐藏index.php
    TP5读取数据概述
    TP5的安装部署概要
    eclipse4.7中文包安装方法。
    利用mysqldump备份magento数据库
    MySQL 基础知识
    PHP 基础知识
    妖怪与和尚过河问题
  • 原文地址:https://www.cnblogs.com/xiao-xue-di/p/9398006.html
Copyright © 2011-2022 走看看