You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:基于组合规则过滤list_parts生成的列表列表

Filtering Partitions in R Using the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:08:28