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?
26⋅26⋅26=263=17576. If you want the letters to be unique, the calculation changes slightly.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With