Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to generate all possible three letter strings?

I am generating all possible three letters keywords e.g. aaa, aab, aac.... zzy, zzz below is my code:

alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']  keywords = [] for alpha1 in alphabets:     for alpha2 in alphabets:         for alpha3 in alphabets:             keywords.append(alpha1+alpha2+alpha3) 

Can this functionality be achieved in a more sleek and efficient way?

like image 889
Aamir Rind Avatar asked Aug 16 '11 05:08

Aamir Rind


People also ask

How many combinations of 3 letters can there be?

26⋅26⋅26=263=17576. If you want the letters to be unique, the calculation changes slightly.

How do you calculate combinations with 3 letters?

You can extend each of these possible two letter words into a three letter word by adding one of 26 possible letters and hence there are 26 × 26 × 26 possible three letter words.

How do you generate all strings in Python?

In Python, we can use the built-in module itertools to get permutations of elements in the list using the permutations() function. However, we can also write your utility function to generate all permutations of a string. We can do this either recursively or iteratively.


1 Answers

keywords = itertools.product(alphabets, repeat = 3) 

See the documentation for itertools.product. If you need a list of strings, just use

keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 3)] 

alphabets also doesn't need to be a list, it can just be a string, for example:

from itertools import product from string import ascii_lowercase keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 3)] 

will work if you just want the lowercase ascii letters.

like image 197
agf Avatar answered Oct 15 '22 07:10

agf