2 条题解

  • 0
    @ 2026-3-26 13:03:29

    NUMPY057 题解:随机放置元素

    题目

    在 n × n 零矩阵中随机放置 p 个 1。

    解题思路

    1. 创建 n × n 零矩阵
    2. 随机选择 p 个位置
    3. 用 \texttt{np.put} 放置 1

    代码

    import numpy as np
    
    n, p = map(int, input().split())
    Z = np.zeros((n, n), dtype=int)
    indices = np.random.choice(n * n, p, replace=False)
    np.put(Z, indices, 1)
    print(Z)
    

    代码详解

    • \texttt{np.zeros((n, n), dtype=int)} —— 创建整数零矩阵
    • \texttt{np.random.choice(n * n, p, replace=False)} —— 随机选 p 个不重复位置
    • \texttt{np.put(Z, indices, 1)} —— 在指定位置放 1

    核心知识点

    1. \texttt{np.zeros} —— 创建零数组
    2. \texttt{np.random.choice} —— 随机选择
    3. \texttt{np.put} —— 放置元素
    • 0
      @ 2026-3-26 13:02:37

      NUMPY057 题解:随机放置元素

      题目

      在 n × n 零矩阵中随机放置 p 个 1。

      解题思路

      1. 创建 n × n 零矩阵
      2. 随机选择 p 个位置
      3. 用 \texttt{np.put} 放置 1

      代码

      import numpy as np
      
      n, p = map(int, input().split())
      Z = np.zeros((n, n), dtype=int)
      indices = np.random.choice(n * n, p, replace=False)
      np.put(Z, indices, 1)
      print(Z)
      

      代码详解

      • \texttt{np.zeros((n, n), dtype=int)} —— 创建整数零矩阵
      • \texttt{np.random.choice(n * n, p, replace=False)} —— 随机选 p 个不重复位置
      • \texttt{np.put(Z, indices, 1)} —— 在指定位置放 1

      核心知识点

      1. \texttt{np.zeros} —— 创建零数组
      2. \texttt{np.random.choice} —— 随机选择
      3. \texttt{np.put} —— 放置元素
      • 1

      信息

      ID
      308
      时间
      1000ms
      内存
      256MiB
      难度
      (无)
      标签
      (无)
      递交数
      0
      已通过
      0
      上传者