python - Using itertools for arbitrary number of nested loops of different ranges with dependencies? -
given list of upperbounds: b1, b2, .. bn;
dependency functions: f1, ..., fn-1,
i'm wondering if there's recipe using itertools or other classes in python for:
for i1 in range(0, b1): i2 in range(f1(i1), b2): ... in in range(fn-1(in-1), bn) dostuff(i1, i2, ... in)
where there n levels of nesting?
want use helper function this:
dependentproducts(bs, fs, dostuff),
returns list or iterable
ideally, implementation iterative instead of recursive.
an iterative solution using @laurentlaporte's setup. put code right under , should work. args
stack of arguments fed dostuff
whenever it's full. actual solution middle part, top , bottom parts testing.
stefan = [] def dostuff(*args): stefan.append(list(args)) args = [-1] while args: n = len(args) args[-1] += 1 if args[-1] >= b[n-1]: args.pop() elif n == len(b): dostuff(*args) else: args.append(f[n](args[-1]) - 1) assert expected == stefan
Comments
Post a Comment