2022年 11月 5日

鱼C_python的一些题

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

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

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

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

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

3.10*10杨辉三角形

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

  1. c = []
  2. # 创建并初始化
  3. for i in range(10):
  4. c.append([])
  5. for j in range(i + 1):
  6. c[i].append(0)
  7. c[i][0] = 1
  8. c[i][i] = 1
  9. # 填数
  10. for i in range(2, 10):
  11. for j in range(1, i):
  12. c[i][j] = c[i - 1][j - 1] + c[i - 1][j]
  13. # 打印
  14. for i in range(10):
  15. lis = [str(i) for i in c[i]] # 将数值列表转化为字符列表
  16. s1 = ' '.join(lis) # 将字符列表中的元素用‘’连接为字符串
  17. 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]]

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

  1. rows = len(matrix)
  2. cols = len(matrix[0])
  3. left = 0
  4. right = cols - 1
  5. top = 0
  6. bottom = rows - 1
  7. result = []
  8. while left <= right and top <= bottom:
  9. # 从左往右遍历
  10. for col in range(left, right + 1):
  11. result.append(matrix[top][col])
  12. # 从上往下遍历
  13. for row in range(top + 1, bottom + 1):
  14. result.append(matrix[row][right])
  15. if left < right and top < bottom:
  16. # 从右往左遍历
  17. for col in range(right - 1, left, -1):
  18. result.append(matrix[bottom][col])
  19. # 从下往上遍历
  20. for row in range(bottom, top, -1):
  21. result.append(matrix[row][left])
  22. left = left + 1
  23. right = right - 1
  24. top = top + 1
  25. bottom = bottom - 1
  26. print(result)