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

如何将基于中间值迭代更新的Python循环改写为递归函数?

Refactoring the For-Loop into a Recursive Function

First, let's recap the core logic of your original code to make sure we replicate it exactly:

  • Start with irrel_pos as the range 3-10 (inclusive)
  • For each number in n_extra_pos, randomly sample that many unique elements from the current irrel_pos
  • Add the sampled elements (as a set) to extra_pos
  • Remove those sampled elements from irrel_pos
  • Once all samples are taken, output the remaining irrel_pos and the list of sampled sets

Here's how we can turn this into a recursive function. The key idea is to process one element from n_extra_pos at a time, then recurse with the updated state:

import numpy as np

def sample_extra_pos(remaining_n, current_irrel_pos, rs, collected_extra=None):
    # Initialize collected_extra on first call if not provided
    if collected_extra is None:
        collected_extra = []
    
    # Termination condition: no more samples to take
    if not remaining_n:
        return current_irrel_pos, collected_extra
    
    # Take the first number of samples needed
    n = remaining_n[0]
    # Convert current_irrel_pos to a list for numpy's choice
    sample = rs.choice(list(current_irrel_pos), n, replace=False)
    sample_set = set(sample)
    
    # Update the collected list and remaining irrel positions
    collected_extra.append(sample_set)
    new_irrel_pos = current_irrel_pos - sample_set
    
    # Recurse with the remaining n values and updated state
    return sample_extra_pos(remaining_n[1:], new_irrel_pos, rs, collected_extra)

# Test it with your original parameters
rs = np.random.RandomState(1)
initial_irrel_pos = set(range(3, 11))  # Convert to set upfront for easier operations
n_extra_pos = [2, 3]

irrel_pos, extra_pos = sample_extra_pos(n_extra_pos, initial_irrel_pos, rs)

print(irrel_pos)
print(extra_pos)

Output Verification

Running this code will produce exactly the same output as your original loop:

{8, 9, 3}
[{10, 5}, {4, 6, 7}]

Key Notes

  • We pass the RandomState object explicitly to ensure the same random sampling behavior across recursive calls (critical for reproducibility)
  • The termination condition checks if remaining_n is empty—once we've processed all elements in n_extra_pos, we return the final state
  • We initialize collected_extra with a None default to avoid common mutable default parameter pitfalls, building up our list of sampled sets recursively

内容的提问来源于stack exchange,提问作者TheRimalaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:28:29