我想要做的就是实现给定here的解决方案(python中的那个) 在R. 我不习惯在R-Studio中进行调试,但即使在我尝试过之后,我仍然无法弄清楚为什么我的代码不起作用。基本上(提供示例输入)我得到了运行所有数字的函数,然后它被卡在一种无限循环(或函数)中。有人可以指出我正确的方向吗?
subset_sum <- function(numbers, target, partial = numeric(0)){
s <- sum(partial,na.rm = TRUE)
# check if the partial sum equals to target
if (s == target){
cat("sum(",partial,")","=",target)
}
else if (s >= target) {
return() # if we reach the number why bother to continue
}
else {
for(i in 1:length(numbers)){
n <- numbers[i]
remaining <- numbers[i+1:length(numbers)]
subset_sum(remaining, target, partial = append(partial,n))
}
}
}
subset_sum(c(3,9,8,4,5,7,10),15)
如果没有在调试模式下运行,它会给我这些错误:
Error: node stack overflow
Error during wrapup: node stack overflow
答案 0 :(得分:1)
这不是一个递归函数,但它利用了R处理矩阵/数组类型数据的能力。某些输出显示在<?php
global $product;
$args = array(
'posts_per_page' => 4,
'orderby' => 'rand',
'post_type' => 'product'
);
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<li class="single_product_lower_widget" style="list-style:none;">
<a href="<?php the_permalink(); ?>">
<span class="single_product_lower_widget_image">
<?php the_post_thumbnail() ?>
<span class="product-title"><?php the_title(); ?></span>
</span>
<p><?php get_post_meta( $post->ID, '_price', true ); ?></p>
</a>
</li>
<?php
endforeach;
wp_reset_postdata();
?>
#
在函数中
v <- c(3,9,8,4,5,7,10)
v <- sort(v)
# [1] 3 4 5 7 8 9 10
target <- 15
# we don't need to check more than at most 4 numbers since 3+4+5+7 (the smallest numbers) is greater than 15
mincombs <- min(which(cumsum(v) > target))
# [1] 4
Combs <- combn(v, mincombs) # make combinations of numbers
ans <- mapply(function(x,y) ifelse(y > 0, paste0(paste0(Combs[1:y,x], collapse="+"), "=", target), NA), 1:ncol(Combs), apply(Combs, 2, function(I) which(cumsum(I) == target)))
ans <- unlist(ans[lengths(ans) > 0])
# [1] "3+4+8=15" "3+4+8=15" "3+5+7=15" "3+5+7=15" "3+5+7=15" "7+8=15"
答案 1 :(得分:1)
这是R
中的递归实现subset_sum = function(numbers,target,partial=0){
if(any(is.na(partial))) return()
s = sum(partial)
if(s == target) print(sprintf("sum(%s)=%s",paste(partial[-1],collapse="+"),target))
if(s > target) return()
for( i in seq_along(numbers)){
n = numbers[i]
remaining = numbers[(i+1):length(numbers)]
subset_sum(remaining,target,c(partial,n))
}
}
我必须在py中添加一个额外的catch来处理i + 1&gt;长度(数字)并返回NA。
> subset_sum(c(3,9,8,4,5,7,10),15)
[1] "sum(3+8+4)=15"
[1] "sum(3+5+7)=15"
[1] "sum(8+7)=15"
[1] "sum(5+10)=15"
我认为(但我不确定)你的问题是if if / else,如果是递归函数中的逻辑。有趣的是,当我将if(i+1 > length(numbers)) return()
置于for循环中时,这破坏了功能,所以我没有得到所有答案 - return
需要在递归之外