My goal is to find any permutation of a diagonal in a nxn matrix (2 <= n <= 15). The matrix consists of zeros and ones.
Currently I do it like this:
indices = [[j for j, x in enumerate(row) if x == 1]
for row in self.matrix]
cart = list(itertools.product(*indices))
cart = [list(tup) for tup in cart]
cart = filter(lambda dia: len(list(set(dia))) == len(dia), cart)
return cart
This works fine if the matrix is not too large, but otherwise it fails with: MemoryError
So is there a way to avoid the whole computation of cart? so that it for example one permutation is found, the computation stops?
itertools.product(*indices)and thecart = [list(tup) for tup in cart]is also unnecessary. Also the filter would be slower than just doing it using a list comp.list(itertools.product(*indices))? You may easily filter data lazily. Can you add information on Python version used? Python 2.x and 3.x would be slightly different here.cart = [p for p in itertools.product(*indices) if len(set(p)) == len(p)]