91divoc
91divoc

Reputation: 5

How to make this faster in generating combinations?

I made a code to generate combinations based on first, second, third, fourth, fifth and sixth input. However, it is taking a long time: it usually takes 86-88 seconds.

Is there a faster and better way to do this?

from itertools import combinations

x = [1, 2, 4, 6, 9, 10, 13, 14, 18, 19, 22, 23, 24, 25, 27, 29, 33, 34, 35, 38, 39, 40, 41, 42]

combi = []

y = []
for c in combinations(x,6):
    combi.append(c)

first =  [1,2,4]
second = [6,9]
third =  [10,13,14,18,22,23,24]
fourth = [19,22,23,27]
fifth =  [25,29,34,35,38,39]
sixth =  [33,38,39,40,41,42]

print("generating...")
for i in combi:
    for a in first:
        for b in second:
            for c in third:
                for d in fourth:
                    for e in fifth:
                        for f in sixth:
                            if i[0] == a and i[1] == b and i[2] == c and i[3] == d and i[4] == e and i[5] == f:
                                y.append(i)
                                break
print(y, '\n')
print(len(y))

Upvotes: 0

Views: 116

Answers (1)

First of all, generating a large number of combinations will always be slow. The first combination call will generate 13K results, which is a lot.

However, your second loop can be made more efficient. It seems like you are checking every combination to see if it is the combination you want. This is inefficient since you are spending a lot of computing power on many combinations that you can eliminate immediately.

Try something like this for the second loop:

for a,b,c,d,e,f in combi:
    if a in first and b in second and c in third and d in fourth and e in fifth and f in sixth:
        y.append((a,b,c,d,e,f))

Alternatively, you can use itertools.product() to replace the entire function (though the order might be slightly different if the order of x is different from the order of the other 6 lists):

y = itertools.product(first, second, third, fourth, fifth, sixth)

Upvotes: 3

Related Questions