Experienced developer learning Python.
I'm iterating through the combinations k at a time from a list of size n. I've been using
from itertools import chain, combinations
for subset in (combinations(range(n), k)) :
doSomethingWith(subset)
Now the problem is that most of the time my doSomethingWith()'s are not productive and I'd like to skip as many of them as I can. And if doSomthingWith() fails for a given subset, I can skip every subset whose rightmost coordinate is larger. In other words if it fails for (1,3,5,8) then the next subset I want to look at is (1,3,6,0), skipping (1,3,5,9), (1,3,5,10), etc.
I realized I need to get explicit control of the loop indices. I need a variable number of nested for loops, using recursion or iteration. Before coding that up I Googled around and found this thread which looks promising.
So now I have:
from itertools import product, repeat
set = range(n)
sets = repeat(set, k)
for subset in list(product(*sets)) :
doSomethingWith(subset)
Beautifully Pythonic but I still have the same problem. I have no way to tell product() when to break out of the innermost loop. What I really want is to be able to pass a callback function into product() so it can execute and optionally break out of the innermost loop.
Any Pythonic suggestions? I'd hate to have to explicitly code variable nested loops or iterate through the return from product() and examine the subsets by hand. That seems so old school :-)