zoukankan      html  css  js  c++  java
  • python——杨辉三角

    1、定义:

    2、基于定义打印

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    n = 6
    triangle = [[1],[1,1]]
    for i in range(2,n):     #已经给出前两行,所以求剩余行
        cur = [1]            #定义每行第一个元素
        pre = triangle[i-1]  #上一行
        for j in range(i-1): #算几次
            cur.append(pre[j] + pre[j+1])
        cur.append(1)
        triangle.append(cur)
    print(triangle)
    
    执行结果:
    [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
    # -*- coding:utf-8 -*-
    # version:python3.7
    
    n = 6
    triangle = []
    for i in range(n):
        cur = [1]
        triangle.append(cur)    #先追加进去
        if i == 0:
            continue
        pre = triangle[i-1]
        for j in range(i-1):
            cur.append(pre[j] + pre[j+1])
        cur.append(1)
    print(triangle)

    3、补0法打印

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    n = 6
    triangle = [[1],[1,1]]
    for i in range(2,n):
        newrow = triangle[i-1]
        newrow.append(0)
        row = [None] * (i+1)    #开辟空间
        for j in range(i+1):
            row[j] = newrow[j-1] + newrow[j]
        triangle.append(row)
    print(triangle)
    
    执行结果:
    [[1], [1, 1, 0], [1, 2, 1, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1, 0], [1, 5, 10, 10, 5, 1]]

    4、根据对称性打印(索引)

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    n = 6
    triangle = [[1],[1,1]]
    for i in range(2,n):
        row = [1] * (i+1)
        for j in range(i//2):    #有图知:大概的临界值为一半,再仔细推敲
            val = triangle[i-1][j] + triangle[i-1][j+1]
            row[j+1] = val
            row[i-j-1] =val      #此处规律:两个对称值的索引和等于 i
        triangle.append(row)
    print(triangle)
    
    执行结果:
    [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]

    5、单个列表覆盖、切片完成

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    n = 6
    row = [1] * n
    for i in range(n):    #n行n次
        old = 1                  #old刚开始为1
        for j in range(i//2):
            val = old + row[j+1]
            old = row[j+1]    #此处现将row[j+1]的值赋给old,以防止被覆盖
            row[j+1] = val
            if i != 2*j:
                row[i-j-1] = val
    
      print(row[:i+1])
    执行结果:
    [1]
    [1, 1]
    [1, 2, 1]
    [1, 3, 3, 1]
    [1, 4, 6, 4, 1]
    [1, 5, 10, 10, 5, 1]
  • 相关阅读:
    Oracle86和92语法的连接,子查询,集合的操作
    Oracle笛卡尔积,分组,多表连接
    Oracle排序,伪列,字符函数,数字函数,日期行数
    Oracle基本的数据类型以及简单sql查询
    用while语句打印阶乘
    Switch小练习
    if语句多表达式与一个表达式
    三元操作符
    整数的二进制表达
    与或
  • 原文地址:https://www.cnblogs.com/zyybky/p/12598095.html
Copyright © 2011-2022 走看看