R语言:基于组合规则过滤list_parts生成的列表列表
partitions Package To solve your problem of filtering out partitions that contain the forbidden block (2,3) without including element 1, here's a step-by-step solution using the partitions package:
Step 1: Load the Package and Generate Partitions
First, we'll load the partitions package and generate all partitions of the number 3 using list_parts(3):
library(partitions) all_partitions <- list_parts(3)
Step 2: Define the Forbidden Block and Filter Function
Next, we define the block we want to exclude (c(2,3)) and a helper function to check if a partition is valid (i.e., it doesn't contain this forbidden block). We use setequal() to ensure we match the block regardless of element order:
forbidden_block <- c(2, 3) is_valid <- function(partition) { # Check if any block in the partition matches the forbidden block !any(sapply(partition, function(block) setequal(block, forbidden_block))) }
Step 3: Apply the Filter
We use R's Filter() function to keep only the valid partitions:
valid_partitions <- Filter(is_valid, all_partitions)
Step 4: View the Result
When you print valid_partitions, you'll see the filtered list excluding the partition with (2,3)(1):
valid_partitions # Output: # [[1]] # [1] (1,2,3) # # [[2]] # [1] (1,3)(2) # # [[3]] # [1] (1,2)(3) # # [[4]] # [1] (1)(2)(3)
Generalizing to Multiple Forbidden Blocks
If you have multiple blocks to exclude, you can extend the solution by using a list of forbidden blocks. For example:
# List of forbidden blocks forbidden_blocks <- list(c(2,3), c(1,3)) is_valid_multiple <- function(partition) { # Check if any block in the partition matches any forbidden block !any(sapply(partition, function(block) { any(sapply(forbidden_blocks, function(fb) setequal(block, fb))) })) } # Apply the filter valid_partitions_multiple <- Filter(is_valid_multiple, all_partitions)
This will exclude any partition that contains either (2,3) or (1,3) as a block.
内容的提问来源于stack exchange,提问作者Rhys

