harshit-sh
harshit-sh

Reputation: 386

Efficient method to get all k combinations of a python list

I used the itertools.combinations(iterable,k) method which is pretty time consuming for large test cases. Is there any method that can make it faster.

For example, I have a list of numbers : [1,2,3]

All possible '2' combinations of the list : [(1,2),(1,3),(2,3)]

Any help is appreciated.

Upvotes: 2

Views: 3051

Answers (1)

sshashank124
sshashank124

Reputation: 32189

itertoools.combinations(i, k) is quite efficient. I suppose the reason you are finding it time consuming is because you are converting the generator to a list right away something along the lines of: list(itertools.combinations(i, k)). However, you can just use the values one-by-one as needed in a for loop something as follows:

for item in itertools.combinations(i, k):
    #do stuff with each combination

Upvotes: 9

Related Questions