如何编写Python脚本生成3x3矩阵并填充所有3格被占的可能组合
Generate All 3x3 Matrices with Exactly 3 Occupied Cells
Got it, let's tackle this problem step by step. We need to generate every possible 3x3 matrix where exactly 3 cells are occupied (we'll use 1 for occupied, 0 for empty to keep things clear).
Approach
- Treat the 3x3 grid as 9 indexed positions (0 to 8). Each index maps to a row/column pair: for index
i, row =i // 3, column =i % 3. - Use
itertools.combinationsto generate all unique sets of 3 positions from the 9 total—this gives us every valid way to choose 3 cells to occupy. - For each combination, create a blank 3x3 matrix filled with
0s, then set the selected positions to1. - Print each matrix with separators to make it easy to distinguish between different combinations.
Complete Python Script
import itertools def generate_3cell_matrices(): # Total cells in a 3x3 grid: 9, indexed 0 through 8 total_cells = 9 # Generate all unique combinations of 3 cell indices for combo in itertools.combinations(range(total_cells), 3): # Initialize an empty 3x3 matrix with 0s matrix = [[0 for _ in range(3)] for _ in range(3)] # Mark the selected cells as occupied (1) for cell_idx in combo: row = cell_idx // 3 col = cell_idx % 3 matrix[row][col] = 1 # Print the matrix with a separator print("--- New Matrix ---") for row in matrix: print(' '.join(map(str, row))) if __name__ == "__main__": generate_3cell_matrices()
How It Works
itertools.combinations(range(9), 3)generates all 84 unique 3-cell combinations (since 9 choose 3 equals 84—no duplicates, no repeats).- The flat index to row/column conversion makes it easy to map the combination values to the 2D matrix.
- The
--- New Matrix ---separator keeps the output organized so you can scan through all combinations without confusion.
Example Output Snippet
You'll see output like this for each unique matrix:
--- New Matrix --- 1 1 1 0 0 0 0 0 0 --- New Matrix --- 1 1 0 1 0 0 0 0 0 --- New Matrix --- 1 1 0 0 1 0 0 0 0 ...
内容的提问来源于stack exchange,提问作者Mohamed Ibrahim
相关产品推荐
相关产品推荐

