Reputation: 1127
I want to generate all possible permutations for specific consonant/vowel setups. For example, I would like all possible 3 letter word permutations with the format of CVC (Consonant, Vowel, Consonant).
I don't know of any way to multiply permutations:
permutations("bcdfghjklmnpqrstvwxyz",1) * permutations("aeiou",1) * permutations("bcdfghjklmnpqrstvwxyz",1)
How can this be achieved in python?
Upvotes: 1
Views: 1675
Reputation: 353389
itertools.product to the rescue:
>>> import itertools
>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> vowels = "aeiou"
>>> poss = list(itertools.product(consonants, vowels, consonants))
>>> len(poss)
2205
>>> poss[:10]
[('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'a', 'd'), ('b', 'a', 'f'), ('b', 'a', 'g'), ('b', 'a', 'h'), ('b', 'a', 'j'), ('b', 'a', 'k'), ('b', 'a', 'l'), ('b', 'a', 'm')]
or if you want words specifically:
>>> words = list(''.join(letters) for letters in itertools.product(consonants, vowels, consonants))
>>> words[:10]
['bab', 'bac', 'bad', 'baf', 'bag', 'bah', 'baj', 'bak', 'bal', 'bam']
Upvotes: 5
Reputation: 363183
Here's a non-itertools based solution:
>>> import string
>>> vowels = set('aeiou')
>>> consonants = set(string.ascii_lowercase) - vowels
>>> cvc_generator = (''.join((c1, v, c2)) for c1 in consonants for v in vowels for c2 in consonants)
>>> cvc_generator.next()
'cac'
>>> cvc_generator.next()
'cab'
>>> cvc_generator.next()
'cad'
>>> cvc_generator.next()
'cag'
>>> print ' '.join(cvc for cvc in cvc_generator)
caf cah cak caj cam cal can caq cap cas car cat caw cav cay cax caz cic cib cid cig cif cih cik cij cim cil cin ciq cip cis cir cit ciw civ ciy cix ciz cec ceb ced ceg cef ceh cek cej cem cel cen ceq cep ces cer cet cew cev cey cex cez cuc cub cud cug cuf cuh cuk cuj cum cul cun cuq cup cus cur cut cuw cuv cuy cux cuz coc cob <..snip..>
Upvotes: 2