Reputation: 101
Which code best generates all 3-letter combinations of a given set of letters in Python? I want to output something like this:
'AAA', 'AAB', 'AAC', 'AAD', 'AAE', 'AAF', 'AAG', 'AAH', 'AAI', 'AAJ', 'AAK', 'AAL', 'AAM'...'ZZX', 'ZZY', 'ZZZ'
Upvotes: 0
Views: 120
Reputation: 190
I think you are looking for itertools.combinations_with_replacement
method
import itertools
for conv in itertools.combinations_with_replacement("abcdefg",r=3):
print(conv)
where r
is the size of every combination.
Upvotes: 0
Reputation: 52008
itertools is a natural choice since these are essentially products drawn from a set of letters.
import string,itertools
words = [''.join(letters) for letters in itertools.product(string.ascii_uppercase,repeat = 3)]
print(words[:5]) #['AAA', 'AAB', 'AAC', 'AAD', 'AAE']
print(words[-5:]) #['ZZV', 'ZZW', 'ZZX', 'ZZY', 'ZZZ']
Upvotes: 1
Reputation: 152
You could do it easy with for loops.
combinations = []
letters = ['A','B','C',....,'Z']
for letter1 in letters:
code = ''
code = code + letter1
for letter2 in letters:
code = code + letter2
for letter3 in letters:
code = code + letter3
combinations.append(code)
Upvotes: 0