开发者

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

开发者 https://www.devze.com 2023-04-08 20:51 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: is there any best way to generate all possible three letters keywords
This question already has answers here: Closed 11 years ago.

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 o开发者_如何学Pythonnes, and discussions of speed considerations.


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


You can use itertools:

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

This gives you 27 elements as you expected.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号