Home > Software engineering >  How to get every possible combination without changing position efficiently?
How to get every possible combination without changing position efficiently?

Time:02-14

I have a list of 2D list which row number is 60 and column number is not fixed. Here, row numbers mean position. How to get every possible combination without changing position?

Let me explain with an example: Let's make it shorter to understand. Let's assume, row number is 3 instead of 60. List:

list_val = [[1, 2, 3], [2, 3], [5]]

I want to get the combination:

{1, 2, 5}, {1, 3, 5}, {2, 2, 5}, {2, 3, 5}, {3, 2, 5}, {3, 3, 5}

For three, it should be easy to write three nested loops. But for 60, writing 60 nested loops is not a good idea. Is there any better efficient way to write code in python?

CodePudding user response:

What you're looking for is itertools.product() which implements it in a reasonably efficient way so that you don't need to reinvent it and it's fine for large iterables.

Why is that? It's implemented in C (1, 2) therefore the performance is faster than with your standard pure-Python implementation of the loops unless you use tricks that could achieve comparable speed.

Don't forget to unpack the iterable that has iterables you want to use with star/asterisk (*) for the function or supply it with multiple variables (product(one, two, three)), otherwise it'll behave differently.

>>> from itertools import product
>>> list(product(*[[1, 2, 3], [2,3], [5]]))
[(1, 2, 5), (1, 3, 5), (2, 2, 5), (2, 3, 5), (3, 2, 5), (3, 3, 5)]
>>> 
  • Related