如何将基于中间值迭代更新的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_posas the range 3-10 (inclusive) - For each number in
n_extra_pos, randomly sample that many unique elements from the currentirrel_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_posand 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
RandomStateobject explicitly to ensure the same random sampling behavior across recursive calls (critical for reproducibility) - The termination condition checks if
remaining_nis empty—once we've processed all elements inn_extra_pos, we return the final state - We initialize
collected_extrawith aNonedefault to avoid common mutable default parameter pitfalls, building up our list of sampled sets recursively
内容的提问来源于stack exchange,提问作者TheRimalaya
相关产品推荐
相关产品推荐

