To solve this problem, we need to generate an n x n permutation matrix—a square matrix where each row and column contains exactly one 1 (and the rest 0s). This is achieved by using a permutation of indices (0 to n-1) to place the 1s in the matrix.
Approach
- Initialize the Matrix: Create an n x n matrix filled with 0s using list comprehensions.
- Choose a Permutation: A permutation of indices (0 to n-1) ensures each row and column gets exactly one 1. For example, a permutation like [2,0,1] for n=3 means row 0 has a 1 at column 2, row 1 at column 0, and row 2 at column 1.
- Fill the Matrix: For each row index
i, set the element at columnpermutation[i]to 1.
Solution Code
n = 3 # Example size (can be any positive integer)
permutation = [2, 0, 1] # Example permutation (valid for n=3)
# Initialize n x n matrix with 0s
matrix = [[0] * n for _ in range(n)]
# Place 1s according to the permutation
for i in range(n):
matrix[i][permutation[i]] = 1
# Print the result
for row in matrix:
print(row)
Explanation
- Matrix Initialization:
[[0]*n for _ in range(n)]creates a 2D list where each sublist (row) hasnzeros. - Permutation: The permutation list defines where to place the 1 in each row. For a valid permutation matrix, the permutation must be a bijection (each index from 0 to n-1 appears exactly once).
- Filling the Matrix: The loop iterates over each row, setting the 1 at the column specified by the permutation for that row. This ensures each row and column has exactly one 1.
Example Output (for n=3 and permutation [2,0,1])
[0, 0, 1]
[1, 0, 0]
[0, 1, 0]
Random Permutation (Optional)
To generate a random permutation matrix, use the random module:
import random
n = 5
permutation = random.sample(range(n), n) # Random permutation of 0..n-1
matrix = [[0]*n for _ in range(n)]
for i in range(n):
matrix[i][permutation[i]] = 1
for row in matrix:
print(row)
This code will produce a random permutation matrix where each row and column has exactly one 1.
The key takeaway is that a permutation matrix is defined by a permutation of indices, and the code correctly implements this logic. ✅


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。