enumerating all possible strings of length K from an alphabet in Python [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-10 10:45:39

问题


Possible Duplicate:
is there any best way to generate all possible three letters keywords

how can I enumerate all strings of length K from an alphabet L, where L is simply a list of characters? E.g. if L = ['A', 'B', 'C'] and K = 2, I'd like to enumerate all possible strings of length 2 that can be made up with the letters 'A', 'B', 'C'. They can be reused, so 'AA' is valid.

This is essentially permutations with replacement, as far as I understand. if theres a more correct technical term for this, please let me know.... its essentially all strings of length K that you can make by choosing ANY letter from the alphabet L, and possibly reusing letters, in a way that is sensitive to order (so AB is NOT identical to BA according to this.) is there a clearer way to state this?

in any case i believe the solution is:

[ ''.join(x) for x in product(L, repeat=K) ]

but i am interested in other answers to this, esp. naive approaches versus fast Pythonic ones, and discussions of speed considerations.


回答1:


this is part of the Python Documentation

EDIT2: of course the right answer is the product, thanks for the comment

print  [''.join(x) for x in product('ABC', repeat=3)]

prints 27 elements

['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 
'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA', 
'CBB', 'CBC', 'CCA', 'CCB', 'CCC']

@agf gave the right answer before




回答2:


You can use itertools:

n = 3
itertools.product(*['abc']*n)

This gives you 27 elements as you expected.



来源:https://stackoverflow.com/questions/7565675/enumerating-all-possible-strings-of-length-k-from-an-alphabet-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!