每日codingame小游戏练习[2021.4.08](python3入门学习之杨辉三角形)

题目描述

Print rows rows of the Pascal’ s triangle but make the first number start he Pascals triangle is a triangle which has one 1 on the top , 2 ones below that . and for the next few rows are the sum of the two numbers above it . There should not be spaces before the first number but put spaces in-between each number .
eg:

InputOutput
5
5
5
5 5
5 10 5
5 15 15 5
5 20 30 20 5

题目分析

题目要求就是让写杨辉三角形,直接上代码。

解题代码

太久不写了,我没出来,下面是我搜到的代码:

n=int(input())
a=int(input())
list1=[]
for n in range(n):
    row=[1] # 第一行第一列为1
    list1.append(row)
    if n==0:
        for num in row:  # 这里主要是为输出做的格式处理
            print(num*a,end=" ")
            print()
        continue
    for m in range(1,n):
        row.append((list1[n-1][m-1]+list1[n-1][m]))
    row.append(1)
    for num in row:
        print(num*a, end=" ")
    print()

法国老哥的代码:

N=int(input())-1
R=[int(input())]
print(*R)
for _ in" "*N:
    l=[R[0]]
    for j in range(len(R)-1):
        l+=[ R[j]+R[j+1] ]
    R=l+[R[0]]
    print(*R)

总结

  1. 在同一循环内,相同的列表,公用同一地址,例如例子一中的list1.append(row)和row在同一列表内公用同一地址,row增加,list1也会跟着增加。
  2. [[] for _ in range(10)]详解 - python
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值