Python Consonant / Vowel Permutations

时间:2012-03-21 03:12:19

标签: python permutation

我想为特定的辅音/元音设置生成所有可能的排列。例如,我希望所有可能的3个字母的单词排列格式为CVC(辅音,元音,辅音)。

我不知道如何增加排列:

permutations("bcdfghjklmnpqrstvwxyz",1) * permutations("aeiou",1) * permutations("bcdfghjklmnpqrstvwxyz",1)

如何在python中实现?

2 个答案:

答案 0 :(得分:4)

itertools.product救援:

>>> 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')]

或者如果你想要特别说明的话:

>>> words = list(''.join(letters) for letters in itertools.product(consonants, vowels, consonants))
>>> words[:10]
['bab', 'bac', 'bad', 'baf', 'bag', 'bah', 'baj', 'bak', 'bal', 'bam']

答案 1 :(得分:2)

这是一个非基于itertools的解决方案:

>>> 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..>