SeekNDstroy
SeekNDstroy

Reputation: 322

Python Combinations with conditions

I have a piece of code and I am using itertools to generate the combinations.

import itertools

charset = list('abcdefghijklmnopqrstuvwxyz'.upper())

for it in itertools.combinations(charset, 16):
    while (it[0] < 'F' and
           it[1] < 'H' and it[1] > 'A' and
           it[2] < 'K' and it[2] > 'B' and
           it[3] < 'L' and it[3] > 'C' and
           it[4] < 'N' and it[4] > 'D' and
           it[5] < 'T' and it[5] > 'G' and
           it[6] < 'V' and it[6] > 'H' and
           it[7] < 'Y' and it[7] > 'I' and
           it[8] < 'Z' and it[8] > 'J' and
           ord(it[9]) < 91):
        print (it)
        break

This gets the job, done but I am trying to look for a better way that can perhaps avoid the checking of the while conditions and directly generate the combinations in order to save time. Is there another itertools function, or something of that sort?

Upvotes: 1

Views: 308

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54668

This creates your first 9 items. If the last 7 are chosen from the whole set, I suppose you could append the result of itertools.combinations(...,7), but since this set will already generate about a billion entries, it's not clear what you'll do with this.

import itertools

items = [ 
  'ABCDE',
  'BCDEFG',
  'CDEFGHIJ',
  'DEFGHIJK',
  'EFGHIJKLM',
  'HIJKLMNOPQRS',
  'IJKLMNOPQRSTU',
  'JKLMNOPQRSTUVWX',
  'KLMNOPQRSTUVWXY'
]

for it in itertools.product(*items):
    print (it)

Upvotes: 1

Related Questions