0

How can I print all possible words of a user-specified length "x" in python? I already know how to do it for a specific number of characters like all possible 3 letter words by using for loops, and don't want a lengthy if-else ladder for each specified length. I was looking for programs that don't use modules, rather loops.

The code I used for a definite length (3 in this case):

for i in range(ord('a'),ord('z')):
    for j in range(ord('a'),ord('z')):
        for k in range(ord('a'),ord('z')):
            print(chr(i)+chr(j)+chr(k));

It prints all words starting from aaa to zzz, but the code starts getting very 'bulky' or 'lengthy' for more iterations.

Is there any shorter or alternative way which can print the words of a user-specified length?

8
  • You can count to 26**x in base 26 (use modulo operations), outputting the corresponding letter for each digit. Commented Dec 16, 2024 at 11:42
  • You need one for loop. One to loop from a to z. Then repeat that char x times before you print. Commented Dec 16, 2024 at 11:47
  • Could you please provide a block of code for further clarification @lastchance? Commented Dec 16, 2024 at 11:54
  • Only if somebody reopens the question, @Aarush Ravez. Not sensible to do within a comment, and it doesn't duplicate any of the answers in the duplicates. There seems to be too much of a rush to use itertools when all somebody is doing is counting. Commented Dec 16, 2024 at 11:56
  • That's what the standard library is for, it makes common tasks easier. Of course you're welcome to reinvent all the wheels yourself: stackoverflow.com/a/3902074/476. Commented Dec 16, 2024 at 12:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.