鱼C_python的一些题

1. 请问下面代码执行后,列表 x 和 y 的内容分别是什么

x = [[1, 2, 3],[4, 5, 6]]
y = x.copy()
y.append(7)
y[1].append(8)
print(y)
print(x)

结果为:
[[1, 2, 3], [4, 5, 6, 8], 7]
[[1, 2, 3], [4, 5, 6, 8]]
 

2. 创建一个88 x 88的随机整数矩阵(二维列表)

matrix = []
for i in range(88):
    matrix.append([])
    for j in range(88):
        matrix[i].append(random.randint(0, 1024))

3.10*10杨辉三角形

重点是center函数的使用,str.center(width),此处的width为总长度

c = []
# 创建并初始化
for i in range(10):
    c.append([])
    for j in range(i + 1):
        c[i].append(0)
    c[i][0] = 1
    c[i][i] = 1
# 填数
for i in range(2, 10):
    for j in range(1, i):
        c[i][j] = c[i - 1][j - 1] + c[i - 1][j]
# 打印
for i in range(10):
    lis = [str(i) for i in c[i]]  # 将数值列表转化为字符列表
    s1 = '    '.join(lis)  # 将字符列表中的元素用‘’连接为字符串
    print(s1.center(80))  # 居中函数,80为总长

结果如下:

                                        1                                        
                                     1    1                                     
                                  1    2    1                                   
                                1    3    3    1                                
                             1    4    6    4    1                              
                          1    5    10    10  5   1  

4. 请按照顺时针螺旋顺序输出矩阵中的所有元素
matrix = [[1, 2, 3, 4],
               [5, 6, 7, 8],
               [9, 10, 11, 12]]

这个题的思路很有意思,有点点像推箱子的游戏,一次转一圈,然后更新边界值

rows = len(matrix)
cols = len(matrix[0])
    
left = 0
right = cols - 1
top = 0
bottom = rows - 1
    
result = []
    
while left <= right and top <= bottom:
    # 从左往右遍历
    for col in range(left, right + 1):
        result.append(matrix[top][col])
    
    # 从上往下遍历
    for row in range(top + 1, bottom + 1):
        result.append(matrix[row][right])
    
    if left < right and top < bottom:
        # 从右往左遍历
        for col in range(right - 1, left, -1):
            result.append(matrix[bottom][col])
    
        # 从下往上遍历
        for row in range(bottom, top, -1):
            result.append(matrix[row][left])
    
    left = left + 1
    right = right - 1
    top = top + 1
    bottom = bottom - 1

print(result)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值